//
//  CMainPageCtrl.m
//  HCHK_iphone
//
//  Created by yilong zhang on 11-12-7.
//  Copyright 2011年 __MyCompanyName__. All rights reserved.
//

#import "CMainPageCtrl.h"

@implementation CMapPageCtrl

static CMapPageCtrl *g_MapPageCtrl = nil;

//topbar
@synthesize m_TopBarView;
@synthesize m_TopLog;
@synthesize m_TopSearchBtn;
@synthesize m_TopRetBtn;
@synthesize m_TopWrite;
@synthesize m_TopOption;
@synthesize m_TopLocation;
@synthesize m_SearchPanel;
@synthesize m_SearchView;
@synthesize m_SearchCancel;
@synthesize m_SearchCover;
@synthesize m_SearchValue;

@synthesize m_BigImageView;
@synthesize m_BigImage;
@synthesize m_BgView;
@synthesize m_bIsBigImageShow;

//root
@synthesize m_bIsHidden;
@synthesize m_Datas;
@synthesize m_Address;
@synthesize m_ItemPreview;
@synthesize m_bIsUpdate;        
@synthesize m_bIsGalleryMoved;
@synthesize m_Command;
@synthesize m_nModel;
//tabview
@synthesize m_TabView;
@synthesize m_nTabPosition;
//root
@synthesize m_DfIcon;
@synthesize m_DfData;
//information
@synthesize m_RightPanel;
@synthesize m_FoodInfoPanel;
@synthesize m_FoodRes;
@synthesize m_FoodName;
@synthesize m_Publisher;
@synthesize m_PinglunBtn;
@synthesize m_UserNick;
@synthesize m_PrdctSum;
@synthesize m_ResBtn;
@synthesize m_PuberBtn;
@synthesize m_PubInfoView;
//topbar
@synthesize m_TopBar;
@synthesize m_ShareBtn;
@synthesize m_MapBtn;
@synthesize m_FavoBtn;
//discussion
@synthesize m_NoComslb;
//@synthesize m_ComsThread;
@synthesize m_ComsIndicator;
@synthesize m_TableView;
@synthesize m_DisDatas;
//bottom
@synthesize m_BottomBar;
@synthesize m_Eatlb;
@synthesize m_Wantlb;
@synthesize m_Nicelb;
//抽屉
@synthesize m_DrawerView;
@synthesize m_IslsideShow;
@synthesize m_lsidepoint;
//地图
@synthesize m_MapPanel;
@synthesize m_MapBack;
@synthesize m_Location;
@synthesize m_Anchor;
@synthesize m_Map;
@synthesize m_Task;
@synthesize m_MapAddr;
//美食
@synthesize m_bIsLoading;
@synthesize m_NativeDBCnt;
@synthesize m_CurPrdct;
//search
@synthesize m_bSearchSwitch;
@synthesize m_bIsVagueSearch;
//share
@synthesize m_Sheet;
//network
@synthesize m_RqstAddr;
@synthesize m_NetCnt;

//shake
@synthesize m_nShakeCnt;
@synthesize m_ShakeStart;
@synthesize m_bIsShake;

//fresh
@synthesize m_bIsFresh;

+(id)allocWithZone:(NSZone *)zone
{
    @synchronized(self)
    {
        if (!g_MainPageCtrl)
        {
            g_MainPageCtrl = [super allocWithZone:zone];
        }
    }
    
    return g_MainPageCtrl;
}

+(CMainPageCtrl*)DefaultMainPageCtrl
{
    if (!g_MainPageCtrl)
    {
        g_MainPageCtrl = [[CMainPageCtrl alloc] init];
    }
    
    return g_MainPageCtrl;
}

+(void)DestroyMainPageCtrl
{
    if (g_MainPageCtrl)
    {
        [g_MainPageCtrl release];
        g_MainPageCtrl = nil;
    }
}

- (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil
{
    self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil];
    if (self) {
        // Custom initialization
    }
    return self;
}

- (void)didReceiveMemoryWarning
{
    // Releases the view if it doesn't have a superview.
    [super didReceiveMemoryWarning];
    
    // Release any cached data, images, etc that aren't in use.
}

#pragma mark - View lifecycle

-(void)dealloc
{
    [m_DisDatas release];
    [m_Datas release];
    [m_DfData release];
    [m_DfIcon release];
    [m_NetCnt release];
    [m_NativeDBCnt release];
    [m_RqstAddr release];
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MSG_LOCATION_RET object:nil];
    
    [super dealloc];
}

- (void)viewDidLoad
{
    [super viewDidLoad];
    //self.view.backgroundColor = [UIColor colorWithRed:0.95 green:0.95 blue:0.95 alpha:1.0];
    self.view.backgroundColor = [UIColor blackColor];
    
    m_bIsGalleryMoved = NO;
    m_bIsLoading = NO;
    m_IslsideShow = NO;
    //m_ComsThread = nil;
    m_bIsUpdate = YES;
    m_bIsBigImageShow = NO;
    m_nModel = 0;
    m_nShakeCnt = 1;
    m_ShakeStart = nil;
    m_bIsShake = NO;
    m_bIsFresh = NO;
    m_bIsHidden= NO;
    m_bSearchSwitch = NO;
    m_bIsVagueSearch= YES;
    
    m_RqstAddr = [[CAddrInfo alloc] init];
    
    m_TopBarView = [[CTopBarView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, TOPBAR_HEIGHT)];
    m_TopBarView.delegate = self;
    [self SetUpTopBar];
    [self.view addSubview:m_TopBarView];
    [m_TopBarView release];
    
    [self SetUpSearchBar];
    
    m_Datas = [[NSMutableArray array] retain];
    
    //from fially to most before
    m_NativeDBCnt = [[CAscCounter alloc] init];
    m_NativeDBCnt.m_nOffset = 0;
    m_NativeDBCnt.m_nLimit  = 6;
    
    //from most before to finally
    m_NetCnt = [[CAscCounter alloc] init];
    m_NetCnt.m_nTotal = 0;
    m_NetCnt.m_nLimit = 6;
    m_NetCnt.m_nOffset= 0;
    m_DfIcon = [[UIImage imageNamed:@"dicon.png"] retain];
    m_DfData = UIImagePNGRepresentation([UIImage imageNamed:@"dimage.png"]);
    [m_DfData retain];

    //地图
    m_Map = [[CMapViewEx alloc] initWithFrame:CGRectMake(0, 0, m_MapPanel.frame.size.width, m_MapPanel.frame.size.height)];
    m_Map.delegate = self;
    [m_MapPanel addSubview:m_Map];
    [m_Map release];
    [m_MapPanel sendSubviewToBack:m_Map];
    m_MapAddr.layer.cornerRadius = 6;
    m_MapAddr.numberOfLines      = 2;
    m_MapAddr.layer.borderWidth  = 1;
    m_MapAddr.layer.borderColor  = [[UIColor lightGrayColor] CGColor];
    
    //地图上的靶心
    m_Anchor = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 35, 35)];
    m_Anchor.center = CGPointMake(m_Map.frame.size.width/2, m_Map.frame.size.height/2);
    m_Anchor.backgroundColor = [UIColor clearColor];
    m_Anchor.image = [UIImage imageNamed:@"anchor.png"];
    [m_MapPanel addSubview:m_Anchor];
    [m_Anchor release];

    //tabview
    /*m_TabView = [[CTabView alloc] initWithFrame:CGRectMake(0, self.view.frame.size.height-TABBAR_HEIGHT, self.view.frame.size.width, TABBAR_HEIGHT)];
    m_TabView.delegate = self;
    m_nTabPosition = m_TabView.m_Tab.m_nFocus;
    [self.view addSubview:m_TabView];
    [m_TabView release];
    [m_TabView CloseTabView];*/
    
    //中部美食浏览
    m_ItemPreview.frame = CGRectMake(0, TOPBAR_HEIGHT, m_ItemPreview.frame.size.width, m_ItemPreview.frame.size.height-10);
    m_ItemPreview.backgroundColor = [UIColor clearColor];
    [m_ItemPreview InitItemPreView];
    m_ItemPreview.m_delegate = self;
    
    //当前位置信息
    /*m_Address = [[UILabel alloc] initWithFrame:CGRectMake((self.view.frame.size.width-PAGE_WIDTH)/2+10, m_TabView.frame.origin.y-4, PAGE_WIDTH-60, 13)];
    m_Address.backgroundColor = [UIColor clearColor];
    m_Address.text = [CLocator DefaultLocator].m_AddrInfo.m_strSum;
    m_Address.font = [UIFont systemFontOfSize:9];
    [self.view addSubview:m_Address];
    [m_Address release];*/
    
    m_PubInfoView = [[CPuberInfoView alloc] initWithFrame:CGRectMake(self.view.frame.size.width, 44, self.view.frame.size.width, self.view.frame.size.height-44)];
    [self.view addSubview:m_PubInfoView];
    [m_PubInfoView release];
    
    [self.view sendSubviewToBack:m_ItemPreview];
    //[self.view bringSubviewToFront:m_Address];
    [self.view bringSubviewToFront:m_TopBar];
    [self.view bringSubviewToFront:m_BottomBar];
    [self.view bringSubviewToFront:m_MapPanel];
    [self.view bringSubviewToFront:m_TabView];
    [self.view bringSubviewToFront:m_SearchCover];
    
    m_BigImageView = [[UIView alloc] initWithFrame:CGRectMake(0, m_TopBarView.frame.size.height, self.view.frame.size.width, self.view.frame.size.height-m_TopBarView.frame.size.height)];
    m_BigImageView.backgroundColor = [UIColor clearColor];
    [self.view addSubview:m_BigImageView];
    [m_BigImageView release];
    
    m_BgView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, m_BigImageView.frame.size.width, m_BigImageView.frame.size.height)];
    m_BgView.backgroundColor = [UIColor blackColor];
    m_BgView.alpha = 0.5;
    [m_BigImageView addSubview:m_BgView];
    [m_BgView release];
    
    m_BigImage = [[UIImageView alloc] initWithFrame:CGRectMake((m_BigImageView.frame.size.width-248)/2, 0, 248, 359)];
    m_BigImage.center = CGPointMake(m_BigImageView.frame.size.width/2, m_BigImageView.frame.size.height/2);
    m_BigImage.layer.shadowOpacity = 0.0;
    m_BigImage.layer.shadowOffset  = CGSizeMake(0, 0);
    m_BigImage.layer.shadowColor   = [[UIColor blackColor] CGColor];
    [m_BigImageView addSubview:m_BigImage];
    [m_BigImage release];
    
    m_BigImage.transform = CGAffineTransformMakeScale(0.1, 0.1);
    m_BigImage.alpha = 0.0;
    m_BigImageView.alpha = 0.0;
    
    //[self InitMainPageView:NO];
    
    //clear buffer of searching
    //[[CDBManager ScheduledShareInstance] ClearTable:@"Search"];
    
    //get data from buffer
    if (![AppConfig DefaultAppConfig].m_bIsNetWork)
    {
        NSArray *prdcts = [self GetProductsFromDB:nil OpIndex:m_TabView.m_Tab.m_nFocus];
        if (prdcts)
        {
            m_bIsUpdate = NO;
            [self AddProductsToTabView:prdcts];
            m_NativeDBCnt.m_nOffset += 6;
        }
        else 
        {
            [[CRootCtrlManager DefaultRootCtrl] ShowAlterView:@"没有可用的数据，网络畅通后再试." State:0];
        }
    }
    //get data from server
    else 
    {
        [self GetProductsFromServer:0/*m_TabView.m_Tab.m_nFocus*/ IsInit:YES Object:[NSNumber numberWithInt:0]];
    }
    
    UIAccelerometer *Accelerometer = [UIAccelerometer sharedAccelerometer];
    Accelerometer.delegate = self;
    Accelerometer.updateInterval = 1.0/60.0;
}

-(void)InitMainPageView:(BOOL)isload
{
    //bigimageview
    if (m_bIsBigImageShow)
    {
        [self HiddenBigImageView];
    }
    
    m_nTabPosition = m_TabView.m_Tab.m_nFocus; 
    
    [self InitMapData];
    [self InitTabViewWithTabFocus:m_nTabPosition];
    [m_Datas removeAllObjects];
    [self InitItemPreView];
    
    //bottombar
    m_Eatlb.text = @"0";
    m_Wantlb.text= @"0";
    m_Nicelb.text= @"0";
    
    //info
    m_FoodName.text = nil;
    m_FoodRes.text  = nil;
    m_Publisher.text= nil;
    m_PrdctSum.text = nil;
    m_UserNick.text = nil;
}

//topbarview
-(void)DidTopBarBtnsClicked:(UIButton*)btn
{
    [self OnTopBarDown:btn];
}

-(void)SetUpTopBar
{
    m_TopBarView.layer.shadowOffset = CGSizeMake(0, 1);
    m_TopBarView.layer.shadowColor  = [[UIColor blackColor] CGColor];
    m_TopBarView.layer.shadowOpacity= 0.8;
    
    m_TopLog = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"hchk.png"]];
    m_TopLog.frame = CGRectMake(0, 0, 64, 21);
    m_TopLog.center= CGPointMake(m_TopBarView.frame.size.width/2, m_TopBarView.frame.size.height/2);
    [m_TopBarView addSubview:m_TopLog];
    [m_TopLog release];
    
    m_TopSearchBtn = [UIButton buttonWithType:UIButtonTypeCustom];
    m_TopSearchBtn.frame = CGRectMake(self.view.frame.size.width-40, 7, 30, 30);//CGRectMake(10, 7, 30, 30);
    [m_TopSearchBtn setBackgroundImage:[UIImage imageNamed:@"search.png"] forState:UIControlStateNormal];
    m_TopSearchBtn.tag = 3;
    [m_TopBarView AddItem:m_TopSearchBtn];
    
    m_TopLocation = [UIButton buttonWithType:UIButtonTypeCustom];
    m_TopLocation.frame = CGRectMake(10, 7, 30, 30);//CGRectMake(self.view.frame.size.width-40, 7, 30, 30);
    m_TopLocation.tag = 2;
    [m_TopLocation setBackgroundImage:[UIImage imageNamed:@"local.png"] forState:UIControlStateNormal];
    [m_TopBarView AddItem:m_TopLocation];
}

-(void)OnTopBarDown:(UIButton*)sender
{
    //return
    if (0 == sender.tag)
    {        
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.4];
        m_PubInfoView.center = CGPointMake(m_PubInfoView.center.x+m_PubInfoView.frame.size.width, m_PubInfoView.center.y);
        [UIView commitAnimations];
    }
    //option
    else if (1 == sender.tag)
    {
        m_Map.m_bTouchEnd = NO;
        //m_TopBarView.hidden = YES;
        [[CRootCtrlManager DefaultRootCtrl] BringCtrlToFront:4];
    }
    //location
    else if (2 == sender.tag)
    {
        if (NormalSupport == [[CLocator DefaultLocator] CheckDevLocation])
        {
            [[CRootCtrlManager DefaultRootCtrl] ShowLoadView:0.8 Title:@"定位中..."];
            
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(LocationMsgListener:) name:MSG_LOCATION_RET object:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(LocationMsgListener:) name:MSG_LOCATION_TIMEOUT object:nil];

            [CLocator DefaultLocator].m_bIsForcedLocal = YES;
            [[CLocator DefaultLocator] StartLocation];
            //NSLog(@"\r\n\r\nfind me\r\n\r\n");
        }
        else if (NetNotSupport != [[CLocator DefaultLocator] CheckDevLocation])
        {
            [[CRootCtrlManager DefaultRootCtrl] ShowLoadView:0.8 Title:@"定位中..."];
            
            //回到启动程序的地理位置
            [self LocationMsgListener:[NSNotification notificationWithName:@"nolocation" object:nil]];
        }
        else {;}
    }
    //search
    else if (3 == sender.tag)
    {
        m_Map.m_bTouchEnd = NO;
        //[[CRootCtrlManager DefaultRootCtrl] BringCtrlToFront:3];
        [self ShowSearchView];
    }
    //write dis
    else if (4 == sender.tag)
    {
        if (Logined == [CUser DefaultUser].m_UType)
        {
            //CProduct *product = [m_Datas objectAtIndex:m_TabView.m_Gallery.m_FocusView.tag];
            [[CRootCtrlManager DefaultRootCtrl] ShowComEditView];
        }
        else 
        {
            UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登陆" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
            [alter show];
            [alter autorelease];
        }
    }
    else {;}
}

-(void)SetUpSearchBar
{
    self.m_SearchValue = @",";
    m_SearchPanel = [[UIView alloc] initWithFrame:CGRectMake(self.view.frame.size.width, 0, self.view.frame.size.width, TOPBAR_HEIGHT)];
    m_SearchPanel.backgroundColor = [UIColor clearColor];
    //m_SearchPanel.clipsToBounds = YES;
    [self.view addSubview:m_SearchPanel];
    [m_SearchPanel release];
    
    UIImageView *searhbg = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, m_SearchPanel.frame.size.width, m_SearchPanel.frame.size.height)];
    searhbg.image = [UIImage imageNamed:@"barbg.png"];
    searhbg.backgroundColor = [UIColor clearColor];
    [m_SearchPanel addSubview:searhbg];
    [searhbg release];
    
    m_SearchView = [[CSearchView alloc] initWithFrame:CGRectMake(0, 0, m_SearchPanel.frame.size.width-60, m_SearchPanel.frame.size.height)];
    m_SearchView.delegate = self;
    [m_SearchPanel addSubview:m_SearchView];
    [m_SearchView release];
    
    m_SearchCancel = [UIButton buttonWithType:UIButtonTypeCustom];
    [m_SearchCancel setBackgroundImage:[UIImage imageNamed:@"button.png"] forState:UIControlStateNormal];
    [m_SearchCancel setTitleColor:[UIColor darkGrayColor] forState:UIControlStateNormal];
    m_SearchCancel.titleLabel.font = [UIFont boldSystemFontOfSize:15];
    m_SearchCancel.frame = CGRectMake(m_SearchPanel.frame.size.width-55, 7, 50, 30);
    [m_SearchCancel setTitle:@"取消" forState:UIControlStateNormal];
    [m_SearchCancel addTarget:self action:@selector(OnSearchCancleDown:) forControlEvents:UIControlEventTouchUpInside];
    [m_SearchPanel addSubview:m_SearchCancel];
    
    m_SearchCover = [[UIView alloc] initWithFrame:CGRectMake(0, TOPBAR_HEIGHT-5, self.view.frame.size.width, self.view.frame.size.height-TOPBAR_HEIGHT+5)];
    m_SearchCover.backgroundColor = [UIColor blackColor];
    m_SearchCover.alpha = 0.0;
    [self.view addSubview:m_SearchCover];
    [m_SearchCover release];
}

-(void)ShowSearchView
{
    [m_SearchView.m_SearchBar becomeFirstResponder];
    
    [UIView beginAnimations:nil context:nil];
    //m_SearchCover.alpha  = 0.5;
    m_SearchPanel.center = CGPointMake(self.view.frame.size.width/2, m_SearchView.center.y);
    if (!m_TopWrite.hidden)
    {
        m_TopWrite.hidden    = YES;
        m_TopLocation.hidden = NO;
        m_TopOption.hidden   = NO;
    }
    [UIView commitAnimations];
}

-(void)SearchViewBecomeFirstResponse
{
    m_SearchCover.alpha = 0.5;
    [m_SearchView.m_SearchBar becomeFirstResponder];
}

-(void)HiddeSearchView
{
    [m_SearchView.m_SearchBar resignFirstResponder];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    m_SearchPanel.center = CGPointMake(self.view.frame.size.width+self.view.frame.size.width/2, m_SearchView.center.y);
    m_SearchCover.alpha = 0.0;
    [UIView commitAnimations];
    
    return;
    
    if (m_SearchCancel.frame.size.width < self.view.frame.size.width)
    {
        [UIView beginAnimations:nil context:nil];
        m_SearchPanel.frame = CGRectMake(self.view.frame.size.width, m_SearchPanel.frame.origin.y, self.view.frame.size.width, m_SearchPanel.frame.size.height);
        m_SearchCover.alpha = 0.0;
        [UIView commitAnimations];
    }
    else 
    {
        [UIView beginAnimations:nil context:nil];
        m_SearchPanel.center = CGPointMake(self.view.frame.size.width+self.view.frame.size.width/2, m_SearchView.center.y);
        m_SearchCover.alpha = 0.0;
        [UIView commitAnimations];
    }
}

-(void)OnSearchCancleDown:(UIButton*)sender
{
    [[CMainPageCtrl DefaultMainPageCtrl] TabSearchAction:0];
    
    [self HiddeSearchView];
}

-(void)DidSearchViewEdited
{
    if (0.0 == m_SearchCover.alpha)
    {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5];
        m_SearchCover.alpha = 0.5;
        if (m_SearchCancel.frame.size.width < self.view.frame.size.width)
        {
            m_SearchPanel.frame = CGRectMake(0, m_SearchPanel.frame.origin.y, self.view.frame.size.width, m_SearchPanel.frame.size.height);
            //m_TopWrite.hidden    = YES;
            //m_TopOption.hidden   = NO;
            //m_TopLocation.hidden = NO;
        }
        [UIView commitAnimations];
    }
}

-(void)DidSearchViewSelected:(int)index Text:(NSString *)text
{
    //1重置搜索条件否则2
    int state = 1;
    if ([self.m_SearchValue isEqualToString:m_SearchView.m_SearchBar.text])
        state = 2;
    else 
        self.m_SearchValue = m_SearchView.m_SearchBar.text;
    
    m_SearchCover.alpha = 0.0;
    
    [[CMainPageCtrl DefaultMainPageCtrl] TabSearchAction:state];
    
    //[self HiddeSearchView];
}

//self
-(void)ShowHomePageCtrl
{
    m_TopBarView.hidden = NO;
}

-(void)HiddenHomePageCtrl
{
    m_TopBarView.hidden = YES;
}

//position
-(NSString*)GetUserPosition
{
    NSString *city = nil;

    //能够通过定位或者地图获得城市
    if ([CLocator DefaultLocator].m_AddrInfo.m_strCity && ([[CLocator DefaultLocator].m_AddrInfo.m_strCity length] > 0))
    {
        city = [NSString stringWithString:[CLocator DefaultLocator].m_AddrInfo.m_strCity];
    }
    
    //hchk-test-start
    if (!city)
    {
        NSLog(@"\r\n\r\n我迷路了，告诉张轶龙（测试用）！\r\n\r\n");
    }
    //hchk-test-end
    
    NSLog(@"\r\n\r\n<========city of user:%@========>\r\n\r\n", city);
    
    return city;
}


//favorite
-(void)DidFavoriteClicked
{
    [[CRootCtrlManager DefaultRootCtrl] ShowLoadView:0.8 Title:@"数据加载中..."];
    m_bIsUpdate = YES;
    [m_TabView.m_Tab AddTabItem:@"收藏"];
    [m_TabView.m_Tab SetFocus:3];
    [self GetProductsFromServer:3 IsInit:YES Object:[NSNumber numberWithInt:0]];
    [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
}

//美食
-(void)InitTabViewWithTabFocus:(int)focus;
{
    [m_TabView InitTabView];
    m_nTabPosition = m_TabView.m_Tab.m_nFocus;
    m_TabView.m_Gallery.m_ItemsData = m_Datas;
    m_TabView.m_Gallery.m_delegate = self;
    m_TabView.delegate = self;
}

-(void)ResetMainView
{
    //GLastestP
    if (0 == m_nTabPosition)
    {
        m_Command = GLastestP;
    }
    //GNearestP
    else if (1 == m_nTabPosition)
    {
        m_Command = GNearestP;
    }
    //GBestP
    else if (2 == m_nTabPosition)
    {
        m_Command = GBestP;
    }
    //GFavoriteP
    else if (3 == m_nTabPosition)
    {
        m_Command = GFavoriteP;
    }
    //GUploadP
    else if (4 == m_nTabPosition)
    {
        m_Command = GUploadP;
    }
    else {;}
    
    [m_TabView ResetTabView];
}

-(void)InitItemPreView
{
    [m_ItemPreview ReSetItemPreView];
}

-(void)AddProductsToTabView:(NSArray*)products
{
    CGalleyItem *item = nil;
    CProduct   *food1 = nil;
    NSData     *data  = nil;
    UIImage    *image = nil;
    int        index  = [m_Datas count];
    BOOL       bIsInit= (0 == [m_Datas count]) ? (YES) : (NO);
    NSMutableArray *arr = [NSMutableArray arrayWithCapacity:[products count]];
    if ([products count] > 0)
    {
        for (int i=0; i<[products count]; i++)
        {
            food1 = (CProduct*)[products objectAtIndex:i];
            food1.m_Index = index++;
            
            if (bIsInit)
            {
                data  = [food1 GetProductIcon];
                if (!data) 
                {
                    [food1 DownLoadIcon];
                }
                else 
                {
                    image = [UIImage imageWithData:data];
                }
            }
            
            item = [[CGalleyItem alloc] initWithImage:image];
            food1.m_IconView = item.m_ImageView;
            [arr addObject:item];
            [item release];
            [m_Datas addObject:food1];
            image = nil;
        }
        
        //添加新数据
        if ([arr count] > 0)
        {
            m_TabView.m_Gallery.m_ItemsData = m_Datas;
            [m_TabView.m_Gallery SetItems:arr Item:nil];
            [m_ItemPreview SetItems:products];
            [[CRootCtrlManager DefaultRootCtrl] RemoveCover];
        }
        
        //初始化
        if (bIsInit)
        {
            m_bIsShake = YES;
            [m_ItemPreview LoadImages:0];
        }
    }
    
    //map model
    if (1 == m_nModel)
    {
        [self SetLocations:products];
    }
    
    m_bIsLoading = NO;
}

-(void)SetProductInfo:(int)index
{
    m_NoComslb.text = @"";
    
    CProduct *product = [m_Datas objectAtIndex:index];
    
    m_CurPrdct = product;
    
    m_FoodRes.text  = product.P_ResName;
    m_FoodName.text = product.P_Name;
    m_PrdctSum.text = product.P_Caption;
    m_UserNick.text = [NSString stringWithFormat:@"%@说:", product.P_PubName];
    NSString *message = nil;                                                                   
    if (/*(Logined == [CUser DefaultUser].m_UType) &&*/ NormalSupport == [[CLocator DefaultLocator] CheckDevLocation])
    {
        double dis = [m_Map GetLocationDistance:[CUser DefaultUser].m_SelfPosition New:CLLocationCoordinate2DMake([product.P_WDu floatValue], [product.P_JDu floatValue])]/1000;
        if (dis < 1)
        {
            dis *= 1000;
            message = [NSString stringWithFormat:@"距离美食%0.2fm", dis];
        }
        else
        {
            message = [NSString stringWithFormat:@"距离美食%0.2fkm", dis];
        }
    }
    else 
    {
        message = [NSString stringWithFormat:@"距离美食%0.2fm", 0.00];
    }
    m_Publisher.text= message;//product.P_PubName;
    
    m_Eatlb.text    = [NSString stringWithFormat:@"%ld", [product.P_Eat longValue]];
    m_Wantlb.text   = [NSString stringWithFormat:@"%ld", [product.P_Want longValue]];
    m_Nicelb.text   = [NSString stringWithFormat:@"%ld", [product.P_Nice longValue]];
    
    //bigimageview
    [self SetBigImageViewImage:product];

    //commentary of product
    [self ShowComsIndicator];
    [m_DisDatas removeAllObjects];
    [product ResetQueryConditions];
    
    [self CommentariesWorker:product];
}

-(void)IsDidProductFavorited:(id)product
{
    NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
    
    if (product == [m_Datas objectAtIndex:m_TabView.m_Gallery.m_FocusView.tag])
    {
        CProduct *p = product;
        CUser    *u = [CUser DefaultUser];
        if (Logined == u.m_UType)
        {
            NSString *c = [[NSString stringWithFormat:@"P_AID == %ld", [p.P_AID longValue]] retain];
            NSArray *rets = [CProduct GetLimitProducts:u.m_FavoriteTable Where:c Offset:0 Limit:1];
            if (rets && [rets count]>0)
            {
                [self performSelectorOnMainThread:@selector(SetDidFavoritedFlag:) withObject:p waitUntilDone:YES];
            }
            else 
            {
                if (p == [m_Datas objectAtIndex:m_TabView.m_Gallery.m_FocusView.tag])
                {
                    [self performSelectorOnMainThread:@selector(SetDidFavoritedFlag:) withObject:nil waitUntilDone:YES];
                }
            }
            
            [c release];
        }
    }
    
    [pool release];
}

-(void)SetDidFavoritedFlag:(id)product
{
    return;
    
    /*if (nil == product)
    {
        [m_ItemPreview SetFavoriteFlag:NO];
    }
    else if (product == [m_Datas objectAtIndex:m_TabView.m_Gallery.m_FocusView.tag])
    {
        [m_ItemPreview SetFavoriteFlag:YES];
    }
    else {;}*/
}

-(void)CancelFavorite
{
    CProduct *product = [m_Datas objectAtIndex:m_TabView.m_Gallery.m_FocusView.tag];
    CLike *like = [[CLike alloc] initWithProduct:product];
    CUser *user = [CUser DefaultUser];
    [like RemoveLike:user.m_FavoriteTable IconPath:user.m_FavoritePath ImagePath:user.m_FavoritePath];
    [like release];
    
    //update user's U_PdtNum property
    if ([[CUser DefaultUser].U_PdtNum longValue] > 0)
    {
        [CUser DefaultUser].U_PdtNum = [NSNumber numberWithLong:[[CUser DefaultUser].U_PdtNum longValue]-1];
        CKey *key = [[CKey alloc] initWithType:1 Value:[CUser DefaultUser].U_PdtNum Name:@"U_PdtNum"];
        [CUser UpadteUserInfo:[NSString stringWithFormat:@"P_AID==%ld", [[CUser DefaultUser].U_PdtNum longValue]] Keys:[NSArray arrayWithObjects:key, nil]];
        [key release];
    }
    
    //[m_ItemPreview SetFavoriteFlag:NO];
}

//美食相关
-(void)CommentariesWorker:(id)object
{
    CProduct *product = object;
    [product GetCommentaries];
}

-(void)ShowComsIndicator
{
    [m_ComsIndicator startAnimating];
}

-(void)HiddenComsIndicator
{
    [m_ComsIndicator stopAnimating];
}

-(IBAction)OnCommitDis:(UIButton*)sender
{
    [[CRootCtrlManager DefaultRootCtrl] ShowComEditView];
    if (Logined == [CUser DefaultUser].m_UType)
    {
        m_TopWrite.hidden    = NO;
        m_TopOption.hidden   = YES;
        m_TopLocation.hidden = YES;
        [[CRootCtrlManager DefaultRootCtrl] ShowComEditView];
    }
    else 
    {
        UIAlertView *login = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登陆" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
        [login show];
        [login autorelease];
    }
}

//好吃，好看，想吃
-(void)DidPingJiaClicked:(int)index
{
    int type = 0;
    //3-好吃
    if (3 == index)
        type = 4;
    //4-好看
    else if (4 == index)
        type = 5;
    //5-想吃
    else if (5 == index)
        type = 6;
    else {;}
    
    [self OnBottomBarBtnDown:type];
}

//same food or restaurant
-(void)DidSameButtonClicked:(int)index Title:(NSString *)title
{
    [[CRootCtrlManager DefaultRootCtrl] HiddenComEditView];
    m_bIsHidden = NO;
    m_bIsVagueSearch = NO;
    
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    btn.tag = 3;
    
    m_SearchView.m_SearchBar.text = title;
    [self OnTopBarDown:btn];
    [self.m_SearchView searchBarSearchButtonClicked:self.m_SearchView.m_SearchBar];
    /*sameres
    if (1 == index)
        m_TabView.m_Tab.m_FocusBtn.titleLabel.text = @"同餐馆";
    else if (2 == index)
        m_TabView.m_Tab.m_FocusBtn.titleLabel.text = @"同类菜";
    else {;}*/
}

//commentary
-(void)DidComEditClicked:(int)index Content:(NSString*)content
{
    if (0 == index)
    {
        [[CRootCtrlManager DefaultRootCtrl] HiddenComEditView];
        m_bIsHidden = NO;
    }
    else if (1 == index)
    {
        [self DidComEditViewCommit:content];
    }
    else {;}
}

/*- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //发表评论内容为空
    if (0 == alertView.tag)
    {
        [[CRootCtrlManager DefaultRootCtrl] HiddenComEditView];
        m_bIsHidden = NO;
    }
}*/

-(void)DidComEditViewCommit:(id)object
{
    CProduct *product = [m_Datas objectAtIndex:m_TabView.m_Gallery.m_FocusView.tag];
    CCommentary *com = [[CCommentary alloc] init];
    NSString *date = [[AppConfig DefaultAppConfig] GetTimeFormatString];
    com.C_AID = [NSNumber numberWithLong:[[AppConfig DefaultAppConfig] DateToInt:date]];
    com.P_AID = product.P_AID;
    com.C_Content = object;
    com.C_Date= com.C_AID;
    com.C_PubID = com.C_AID;
    com.C_PubNick = [CUser DefaultUser].U_Nick;
    [com SaveCommentary];
    
    [product PublicationCommentary:[CUser DefaultUser].U_Token SessionID:[CUser DefaultUser].U_Session Content:com.C_Content TmpID:com.C_AID];

    [com release];
    
    //update user's U_DisNum property
    [CUser DefaultUser].U_DisNum = [NSNumber numberWithLong:[[CUser DefaultUser].U_DisNum longValue]+1];
    CKey *key = [[CKey alloc] initWithType:1 Value:[CUser DefaultUser].U_DisNum Name:@"U_DisNum"];
    [CUser UpadteUserInfo:[NSString stringWithFormat:@"U_AID==%ld", [[CUser DefaultUser].U_AID longValue]] Keys:[NSArray arrayWithObjects:key, nil]];
    [key release];
}

-(void)DidDownLoadImage:(id)product Image:(NSData *)image
{
    //CProduct *P = [m_Datas objectAtIndex:m_TabView.m_Gallery.m_FocusView.tag];
    if (product == m_CurPrdct)
    {
        //[m_ItemPreview SetImageWithImage:1 Data:image];

        [self SetBigImageViewImage:product];
    }
}

-(void)DidDownLoadCommentaries:(id)product Commetaries:(NSArray *)coms
{
    if (product == [m_Datas objectAtIndex:m_TabView.m_Gallery.m_FocusView.tag])
    {
        CCommentary *com = nil;
        for (int i=[coms count]-1; i>=0; i--)
        {
            com = [coms objectAtIndex:i];
            [m_DisDatas addObject:com];
        }
        
        if ([coms count] > 0)
        {
            [m_TableView reloadData];
        }
    }
    
    [self HiddenComsIndicator];
}

-(void)DidDownLoadError:(id)product OpType:(int)optype
{
    CProduct *curproduct =  [m_Datas objectAtIndex:m_TabView.m_Gallery.m_FocusView.tag];
    
    //commentaries of the product
    if (2 == optype && product == curproduct)
    {
        [self HiddenComsIndicator];
        if (0 == [self.m_DisDatas count])
        {
            m_NoComslb.text = @"目前还没有评论";
        }
    }
    //public commentay
    else if (4 == optype)
    {
        //
    }
}

-(void)DidDownLoadSuccess:(id)product OpType:(int)optype Index:(int)index Info:(NSString *)info
{
    CNoticeView *notice = nil;
    CProduct    *prdct  = product;
    
    //commitpingjia
    if (3 == optype)
    {
        if ([m_Datas objectAtIndex:m_TabView.m_Gallery.m_FocusView.tag] == prdct)
        {
            CPreItem *item = [[m_TabView.m_Gallery.m_RootPanel subviews] objectAtIndex:m_TabView.m_Gallery.m_FocusView.tag];
            
            NSString *tablename = nil;
            if (0 == m_TabView.m_Tab.m_nFocus)
            {
                tablename = [NSString stringWithString:@"Best"];
            }
            else if (1 == m_TabView.m_Tab.m_nFocus)
            {
                tablename = [NSString stringWithString:@"Nearest"];
            }
            else if (2 == m_TabView.m_Tab.m_nFocus)
            {
                tablename = [NSString stringWithString:@"Newest"];
            }
            else {;}
            
            //del
            if (0 == index)
            {
                item.m_DelBtn.titleLabel.text = [NSString stringWithFormat:@"%d", [prdct.P_Eat longValue]];
            }
            //want
            else if (1 == index)
            {
                item.m_WantBtn.titleLabel.text = [NSString stringWithFormat:@"%d", [prdct.P_Want longValue]];
            }
            //nice
            else if (2 == index)
            {
                item.m_NiceBtn.titleLabel.text = [NSString stringWithFormat:@"%d", [prdct.P_Nice longValue]];
            }
            else {;}
        }
        
        notice = [[CNoticeView alloc] initWithFrame:CGRectMake(220, 317, 100, 30)];
        [self.view addSubview:notice];
        [notice release];
        [notice Show:info];
    }
}

//tab
-(void)TabViewClickIndex:(int)index
{    
    if (m_nTabPosition != index)
    {
        [[CRootCtrlManager DefaultRootCtrl] ShowLoadView:0.8 Title:@"数据获取中..."];
        [m_TabView HiddenIndicator];
        
        m_bIsUpdate = YES;
            
        if (NormalSupport != [[CLocator DefaultLocator] StartLocation])
        {
            //不能定位
            [self TabChangedLoctionListener:nil];
        }
        else 
        {
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TabChangedLoctionListener:) name:MSG_LOCATION_RET object:nil];
            [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(TabChangedLoctionListener:) name:MSG_LOCATION_TIMEOUT object:nil];
        }
    }
}

//tab改变时，定位监听
-(void)TabChangedLoctionListener:(NSNotification*)notification
{
    //取消tab改变时的定位监听
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MSG_LOCATION_RET object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MSG_LOCATION_TIMEOUT object:nil];
    
    //开始获取数据
    //best
    if (0 == m_TabView.m_Tab.m_nFocus)
    {
        [self TabBestAction];
    }
    //nearest
    else if (1 == m_TabView.m_Tab.m_nFocus)
    {
        [self TabNearestAction];
    }
    //newest
    else if (2 == m_TabView.m_Tab.m_nFocus)
    {
        [self TabNewestAction];
    }
    //search
    else if (3 == m_TabView.m_Tab.m_nFocus)
    {
        //[self TabFavoriteAction];
        [self TabSearchAction:1];
    }
    //upload
    else if (4 == m_TabView.m_Tab.m_nFocus)
    {
        [self TabUploadAction];
    }
    //search
    else if (5 == m_TabView.m_Tab.m_nFocus)
    {
        int state = 1;
        if ([self.m_SearchValue isEqualToString:m_SearchView.m_SearchBar.text])
            state = 2;
        else 
            self.m_SearchValue = m_SearchView.m_SearchBar.text;
        
        [self TabSearchAction:state];
    }
    else {;}
}

-(void)DidTabFocusSeted:(int)index
{
    return;
    
    //best
    if (0 == m_TabView.m_Tab.m_nFocus)
    {
        m_TopSearchBtn.hidden = NO;
    }
    //nearest
    else if (1 == m_TabView.m_Tab.m_nFocus)
    {
        m_TopSearchBtn.hidden = NO;
    }
    //newest
    else if (2 == m_TabView.m_Tab.m_nFocus)
    {
        m_TopSearchBtn.hidden = NO;
    }
    //favorite
    else if (3 == m_TabView.m_Tab.m_nFocus)
    {
        m_TopSearchBtn.hidden = YES;
    }
    //upload
    else if (4 == m_TabView.m_Tab.m_nFocus)
    {
        m_TopSearchBtn.hidden = YES;
    }
    //search
    else if (5 == m_TabView.m_Tab.m_nFocus)
    {
        m_TopSearchBtn.hidden = NO;
    }
    else {;}
}

-(void)TabViewIsOpended:(BOOL)istate
{
    return;
    
    float fh = m_TabView.frame.origin.y - m_MapPanel.frame.origin.y;
    
    //open
    if (istate)
    {
        [UIView beginAnimations:nil context:nil];
        m_Map.frame = CGRectMake(m_Map.frame.origin.x, m_Map.frame.origin.y, m_Map.frame.size.width, fh);
        //m_ItemPreview.m_RootPanel.frame = CGRectMake(m_ItemPreview.m_RootPanel.frame.origin.x, m_ItemPreview.m_RootPanel.frame.origin.y, m_ItemPreview.m_RootPanel.frame.size.width, fh);
        m_Anchor.center = CGPointMake(m_Anchor.center.x, m_Map.center.y);
        [UIView commitAnimations];
    }
    //close
    else 
    {
        [UIView beginAnimations:nil context:nil];
        if (0 == m_nModel)
            [UIView setAnimationDuration:0.5];
        m_Map.frame = CGRectMake(m_Map.frame.origin.x, m_Map.frame.origin.y, m_Map.frame.size.width, fh);
        //m_ItemPreview.m_RootPanel.frame = CGRectMake(m_ItemPreview.m_RootPanel.frame.origin.x, m_ItemPreview.m_RootPanel.frame.origin.y, m_ItemPreview.m_RootPanel.frame.size.width, fh);
        m_Anchor.center = CGPointMake(m_Anchor.center.x, m_Map.center.y);
        [UIView commitAnimations];
    }
}

- (void)viewDidUnload
{
    [super viewDidUnload];
    // Release any retained subviews of the main view.
    // e.g. self.myOutlet = nil;
}

- (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation
{
    // Return YES for supported orientations

    return (interfaceOrientation == UIInterfaceOrientationPortrait) || (interfaceOrientation == UIInterfaceOrientationPortraitUpsideDown);
}

-(void)SetButtomInfo:(CProduct*)product
{
    //设置当前美食最好，想吃，最新
    m_Eatlb.text    = [NSString stringWithFormat:@"%ld", [product.P_Eat longValue]];
    m_Wantlb.text   = [NSString stringWithFormat:@"%ld", [product.P_Want longValue]];
    m_Nicelb.text   = [NSString stringWithFormat:@"%ld", [product.P_Nice longValue]];
}

-(void)DidGallerySelected:(int)index Directory:(int)directory Object:(id)object
{
    CGRect frame = CGRectMake(index*PAGE_WIDTH, 0, PAGE_WIDTH, PANEL_HEIGHT);
    [m_ItemPreview LoadImages:index];
    [m_ItemPreview.m_RootPanel scrollRectToVisible:frame animated:YES];
    
    //地图模式设置标注位置
    if (1 == m_nModel)
    {
        if (m_TabView.m_Gallery.m_FocusView.tag < [m_Map.m_Pins count])
        {
            MapAnnotation *pin = [m_Map.m_Pins objectAtIndex:m_TabView.m_Gallery.m_FocusView.tag];
            (!pin.bIsNull) ? ([m_Map ShowSelPin:pin]) : (nil);
        }
    }
}

-(void)CheckPdtIsFavorite:(CPreItem*)item
{
    if (Logined == [CUser DefaultUser].m_UType)
    {
        CProduct *product = item.m_Product;
        
        NSArray *ret = [[CDBManager ScheduledShareInstance] QueryRecordsFromCursor:[NSString stringWithFormat:@"%@_favorite", [CUser DefaultUser].U_Name] Keys:[NSArray arrayWithObjects:@"P_AID", nil] Offset:0 Limit:1 Column:Product_Properties_Num Condition:[NSString stringWithFormat:@"P_AID=%ld", [product.P_AID longValue]]];
        if ([ret count] > 0)
        {
            item.m_bIsFavorite = NO;
        }
        else 
        {
            item.m_bIsFavorite = YES;
        }
    }
}

-(void)DidPreViewScrollEnd:(id)object
{
    [m_TabView ShowIndicator];
    [self GetMoreDatas];
}

-(void)PreViewDidEndDecelerating:(int)index Directory:(int)directory Object:(CPreItem *)object
{
    //[m_TabView.m_Gallery SetFocusPosition:index];
    [self CheckPdtIsFavorite:object];
}

-(void)PreViewDidSelected:(int)index Object:(CPreItem*)object
{
    if (index < 3)
    {
        [self OnTopBarBtnDown:index];
    }
    else if (index > 3)
    {
        [self OnBottomBarBtnDown:index];
    }
    else if (3 == index)
    {
        CProduct *product = object.m_Product;
        [[CRootCtrlManager DefaultRootCtrl].m_ComEdit SetComEditViewInfo:product Item:object];
        [[CRootCtrlManager DefaultRootCtrl] ShowComEditView];
    }
    else {;}
}

-(void)PreViewDidPublisherInfo
{
    //m_TopBarView.m_Search.hidden = YES;
    //[self OnPuberBtnDown:nil];
}

-(void)PreViewDidWritenCom:(int)state
{
    //关闭
    if (0 == state)
    {
        //searchbar shown
        if (m_SearchPanel.frame.size.width < self.view.frame.size.width)
        {
            [UIView beginAnimations:nil context:nil];
            m_SearchPanel.frame = CGRectMake(m_SearchPanel.frame.origin.x, m_SearchPanel.frame.origin.y, self.view.frame.size.width, m_SearchPanel.frame.size.height);
            [UIView commitAnimations];
        }
        m_TopWrite.hidden    = YES;
        m_TopLocation.hidden = NO;
        m_TopOption.hidden   = NO;
        
        m_bIsHidden = NO;
    }
    //打开
    else 
    {
        m_TopLocation.hidden = YES;
        m_TopOption.hidden   = YES;
        m_TopWrite.hidden    = NO;
        
        //searchbar shown
        if (self.view.frame.size.width/2 == m_SearchPanel.center.x)
        {
            [UIView beginAnimations:nil context:nil];
            m_SearchPanel.frame = CGRectMake(m_SearchPanel.frame.origin.x, m_SearchPanel.frame.origin.y, m_SearchPanel.frame.size.width-60, m_SearchPanel.frame.size.height);
            [UIView commitAnimations];
        }
        
        m_bIsHidden = YES;
    }
    
    //[self OnCommitDis:nil];
}

-(void)PreViewTapImage:(UIImage *)image
{
    return;
    
    [self ShowBigImageView:image];
}

-(void)DidGalleryTurnPage:(int)index Directory:(int)directory Object:(id)object
{
    //NSLog(@"<========DidGalleryTurnPage___Start(Focus:%d___Total:%d)========>", index, [m_Datas count]);
    
    CProduct *product = nil;
    CGalleyItem *item = nil;
    NSArray *subs = [m_TabView.m_Gallery.m_RootPanel subviews];
    NSData *data = nil;
    UIImage*image= nil;
    int start = 0;
    int cnt   = 0;
    int total = [[m_TabView.m_Gallery.m_RootPanel subviews] count] - 1;//[m_Datas count]-1;
    
    //left + 
    if (0 == directory)
    {
        //释放图片
        cnt   = (index >= 5) ? (5) : (index);
        start = index - 1;
        for (int i=0; i<cnt; i++)
        {
            //NSLog(@"释放图片");
            if (start < [m_Datas count])
            {
                product = [m_Datas objectAtIndex:start];
                [product ProductCancelLoadIcon];
                item = [subs objectAtIndex:start--];
                item.m_ImageView.image = nil;
            }
        }
        //加载图片
        cnt = (index+6 <= total) ? (6) : (total - index);
        start = index;
        (start+cnt <= total) ? (++cnt) : (cnt);
        for (int i=0; i<cnt; i++)
        {
            //NSLog(@"加载图片");
            if (start < [m_Datas count])
            {
                product = [m_Datas objectAtIndex:start];
                item = [subs objectAtIndex:start++];
                if (!item.m_ImageView.image)
                {
                    data = [product GetProductIcon];
                    if (data)
                    {
                        image = [UIImage imageWithData:data];
                    }
                    item.m_ImageView.image = image;
                    image = nil;
                }
            }
        }
    }
    //right <-
    else if (1 == directory)
    {
        //加载图片
        cnt   = (index >= 5) ? (5) : (index);
        (0 == index) ? (start=index, cnt=1) : (start=index - 1);
        for (int i=0; i<cnt; i++)
        {
            //NSLog(@"加载图片");
            if (start < [m_Datas count])
            {
                product = [m_Datas objectAtIndex:start];
                item = [subs objectAtIndex:start--];
                if (!item.m_ImageView.image)
                {
                    data = [product GetProductIcon];
                    if (data)
                    {
                        image = [UIImage imageWithData:data];
                    }
                    item.m_ImageView.image = image;
                    image = nil;
                }
            }
        }
        //释放图片
        cnt = (index+12 <= total) ? (6) : (total - (index+6));
        start = index+6;
        for (int i=0; i<cnt; i++)
        {
            //NSLog(@"释放图片");
            if (start < [m_Datas count])
            {
                product = [m_Datas objectAtIndex:start];
                [product ProductCancelLoadIcon];
                item = [subs objectAtIndex:start++];
                item.m_ImageView.image = nil;
            }
        }
    }
    else {;}
    
    //NSLog(@"<========DidGalleryTurnPage___End========>");
}

-(void)DidGalleryDragEnd:(id)object
{
    [m_TabView ShowIndicator];
}

-(void)GetMoreDatas
{
    if (!m_bIsLoading)
    {
        m_bIsLoading = YES;
        
        NSArray *rets = nil;
        //get data from buffer,普通模式
        if ((4 == m_TabView.m_Tab.m_nFocus) || (5 == m_TabView.m_Tab.m_nFocus))
        {
            rets = [self GetProductsFromDB:nil OpIndex:m_TabView.m_Tab.m_nFocus];
            //本地无数据则向服务器请求
            if (rets)
            {
                [self AddProductsToTabView:rets];
                m_NativeDBCnt.m_nOffset += 6;
                m_bIsLoading = NO;
                
                [m_TabView HiddenIndicator];
            }
            else 
            {
                if ([AppConfig DefaultAppConfig].m_bIsNetWork)
                {
                    m_NetCnt.m_nOffset = [m_Datas count];
                    m_NetCnt.m_nLimit  = 6;
                    [self GetProductsFromServer:m_TabView.m_Tab.m_nFocus IsInit:NO Object:[NSNumber numberWithInt:0]];
                }
                else 
                {
                    m_bIsLoading = NO;
                    [m_TabView HiddenIndicator];
                }
            }
        }
        else 
        {
            if (![AppConfig DefaultAppConfig].m_bIsNetWork)
            {
                rets = [self GetProductsFromDB:nil OpIndex:m_TabView.m_Tab.m_nFocus];
                //本地无数据则向服务器请求
                if (rets)
                {
                    [self AddProductsToTabView:rets];
                    m_NativeDBCnt.m_nOffset += 6;
                    m_bIsLoading = NO;
                    
                    [m_TabView HiddenIndicator];
                }
                else 
                {
                    m_bIsLoading = NO;
                    [m_TabView HiddenIndicator];
                }
            }
            else 
            {
                m_NetCnt.m_nOffset = [m_Datas count];
                m_NetCnt.m_nLimit  = 6;
                [self GetProductsFromServer:m_TabView.m_Tab.m_nFocus IsInit:NO Object:[NSNumber numberWithInt:0]];
            }
        }
    }
}

-(void)DidGalleryBottom:(id)object
{
    [self GetMoreDatas];
}

-(void)scrollViewDidScroll:(UIScrollView *)scrollView
{
    if ([m_Datas count] > 0)
    {
        CProduct *product = [m_Datas objectAtIndex:m_TabView.m_Gallery.m_FocusView.tag];
        
        //get more commentaries
        if (m_TableView == scrollView)
        {
            CGPoint point = scrollView.contentOffset;
            if (((point.y+scrollView.frame.size.height) - scrollView.contentSize.height > 50))
            {
                [product GetCommentaries];
            }
        }
    }
}

//topbar
-(void)OnTopBarBtnDown:(int)index
{
    //是否有数据
    if ([m_Datas count] > 0)
    {
        //favorite
        if (0 == index)
        {   
            [self FavoriteAction];
        }
        //share
        else if (1 == index)
        {
            [self ShareAction];
        }
        //map model
        else if (2 == index)
        {
            self.m_RqstAddr.m_strCity     = [NSString stringWithFormat:@"%@",[CLocator DefaultLocator].m_AddrInfo.m_strCity];
            self.m_RqstAddr.m_strProvince = [NSString stringWithFormat:@"%@",[CLocator DefaultLocator].m_AddrInfo.m_strProvince];
            self.m_RqstAddr.m_strCountry  = [NSString stringWithFormat:@"%@",[CLocator DefaultLocator].m_AddrInfo.m_strCountry];
            self.m_RqstAddr.m_fX          = [CLocator DefaultLocator].m_AddrInfo.m_fX;
            self.m_RqstAddr.m_fY          = [CLocator DefaultLocator].m_AddrInfo.m_fY;
            
            NSLog(@"\r\n\r\n切换到地图的城市:%@\r\n\r\n", self.m_RqstAddr.m_strCity);
            
            [self ShowMapView];
        }
        else {;}
    }
}

-(void)ShareAction
{
    if (Logined == [CUser DefaultUser].m_UType)
    {
        //[[CRootCtrlManager DefaultRootCtrl] ShowShareView];
        if (!m_Sheet)
        {
            m_Sheet = [[UIActionSheet alloc] initWithTitle:nil delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"取消" otherButtonTitles:@"腾讯微博分享", @"新浪微博分享", @"邮件分享", nil];
            m_Sheet.actionSheetStyle = UIActionSheetStyleBlackTranslucent;
            [m_Sheet showInView:[CRootCtrlManager DefaultRootCtrl].view];
        }
    }
    else 
    {
        /*UIAlertView *login = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登陆" delegate:nil
                                              cancelButtonTitle:@"关闭" otherButtonTitles:nil];
        [login show];
        [login autorelease];*/
        
        [[CRootCtrlManager DefaultRootCtrl].m_TabBar DidTabBarItemSelected:[[CRootCtrlManager DefaultRootCtrl].m_TabBar.m_Items objectAtIndex:2]];
    }
}

- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    //sina
    if (2 == buttonIndex)
    {
        if (1 == [[CUser DefaultUser].U_SinaOn intValue])
        {
            [CSinaWeibo DefaultSinawb].m_SinaWeiboDelegate = self;
            [[CSinaWeibo DefaultSinawb] LoginSinaWeibo:[CRootCtrlManager DefaultRootCtrl] Name:[CUser DefaultUser].U_Name];
        }
        else 
        {
            UIAlertView *login = [[UIAlertView alloc] initWithTitle:@"提示" message:@"新浪微博分享功能未打开" delegate:nil
                                                  cancelButtonTitle:@"关闭" otherButtonTitles:nil];
            [login show];
            [login autorelease];
        }
    }
    //qq
    else if (1 == buttonIndex)
    {
        if (1 == [[CUser DefaultUser].U_QqOn intValue])
        {
            [CQWeiBo DefaultQQwb].m_QWeiboDelegate = self;
            [[CQWeiBo DefaultQQwb] LoginQQWeibo:[CRootCtrlManager DefaultRootCtrl] Name:[CUser DefaultUser].U_Name];
        }
        else 
        {
            UIAlertView *login = [[UIAlertView alloc] initWithTitle:@"提示" message:@"腾讯微博分享功能未打开" delegate:nil
                                                  cancelButtonTitle:@"关闭" otherButtonTitles:nil];
            [login show];
            [login autorelease];
        }
    }
    //email
    else if (3 == buttonIndex)
    {
        [self DidEmailShare];
    }
    else {;}
    
    [m_Sheet release];
    m_Sheet = nil;
}

-(void)FavoriteAction
{
    CUser *user = [CUser DefaultUser];
    //登陆用户
    if (Logined == user.m_UType)
    {
        m_FavoBtn.enabled = NO;
        
        int nindex = m_TabView.m_Gallery.m_FocusView.tag;
        if (nindex >= 0 && nindex < [m_Datas count])
        {
            CProduct *product = [m_Datas objectAtIndex:m_TabView.m_Gallery.m_FocusView.tag];
            [product retain];
            
            ///(为了避免数据的重复，不再此时保存到本地数据库中)
            [self CommitFavorite:[NSString stringWithFormat:@"%lld", [product.P_AID longLongValue]]];
            [product release];
            /*if ([user SaveFavorite:product])
            {
                //已经收藏
                UIAlertView *fa = [[UIAlertView alloc] initWithTitle:@"提示" message:@"你已经收藏过了。" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles: nil];
                [fa show];
                [fa autorelease];
            }
            else 
            {
                //未收藏向服务器发送收藏结果
                [self CommitFavorite:[NSString stringWithFormat:@"%lld", [product.P_AID longLongValue]]];
                //update user's U_FrdNum Property
                [CUser DefaultUser].U_PdtNum = [NSNumber numberWithLong:[[CUser DefaultUser].U_PdtNum longValue]+1];
                 CKey *key = [[CKey alloc] initWithType:1 Value:[CUser DefaultUser].U_PdtNum Name:@"U_PdtNum"];
                 [CUser UpadteUserInfo:[NSString stringWithFormat:@"P_AID==%ld", [[CUser DefaultUser].U_PdtNum longValue]] Keys:[NSArray arrayWithObjects:key, nil]];
                 [key release];
            }*/
        }
    }
    //未登陆
    else 
    {
        /*UIAlertView *login = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登陆" delegate:nil
                                              cancelButtonTitle:@"关闭" otherButtonTitles:nil];
        [login show];
        [login autorelease];*/
        
        [[CRootCtrlManager DefaultRootCtrl].m_TabBar DidTabBarItemSelected:[[CRootCtrlManager DefaultRootCtrl].m_TabBar.m_Items objectAtIndex:2]];
    }
}

-(void)ShowTopBar:(BOOL)isShow
{
    if (isShow)
    {
        m_TopBar.hidden = NO;
    }
    else 
    {
        m_TopBar.hidden = YES;
    }
}

//in form of email
- (void)mailComposeController:(MFMailComposeViewController *)controller didFinishWithResult:(MFMailComposeResult)result error:(NSError *)error 
{
    switch (result)
    {
        case MFMailComposeResultCancelled:
            //message.text = @"Result: canceled";
            break;
        case MFMailComposeResultSaved:
            //message.text = @"Result: saved";
            break;
        case MFMailComposeResultSent:
            //message.text = @"Result: sent";
            break;
        case MFMailComposeResultFailed:
            //message.text = @"Result: failed";
            break;
        default:
            //message.text = @"Result: not sent";
            break;
    }
    [controller dismissModalViewControllerAnimated:YES];
}

-(void)DisplayComposerSheet
{
    MFMailComposeViewController *picker = [[MFMailComposeViewController alloc] init];
    picker.mailComposeDelegate = self;
    
    CProduct *product = [m_Datas objectAtIndex:m_TabView.m_Gallery.m_FocusView.tag];
    NSData *data = [product GetProductImage];
    if (!data)
    {
        data = m_DfData;
    }
    [picker setSubject:@"好吃客"];
    [picker addAttachmentData:data mimeType:@"png" fileName:[NSString stringWithFormat:@"%@.png", product.P_Name]];
    NSString *emailBody = @"好吃客，好时刻，你我共分享。";
    [picker setMessageBody:emailBody isHTML:NO];
    
    
    [[CRootCtrlManager DefaultRootCtrl] presentModalViewController:picker animated:YES];
    [picker release];
}

-(void)DidEmailShare
{
    Class mailClass = (NSClassFromString(@"MFMailComposeViewController"));
    if (mailClass != nil)
    {
        if ([mailClass canSendMail])
        {
            [self DisplayComposerSheet];
        }
        else
        {
            UIAlertView *email = [[UIAlertView alloc] initWithTitle:@"提示" message:@"你还未对邮件进行设置（发送服务器）。" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
            [email show];
            [email autorelease];
        }
    }
    else
    {
        UIAlertView *email = [[UIAlertView alloc] initWithTitle:@"提示" message:@"设备不支持邮件功能。" delegate:nil cancelButtonTitle:@"知道了" otherButtonTitles:nil];
        [email show];
        [email autorelease];
    }
}

-(void)ClickButtonIndex:(int)index
{
    //sina
    if (0 == index)
    {
        if (1 == [[CUser DefaultUser].U_SinaOn intValue])
        {
            [CSinaWeibo DefaultSinawb].m_SinaWeiboDelegate = self;
            [[CSinaWeibo DefaultSinawb] LoginSinaWeibo:[CRootCtrlManager DefaultRootCtrl] Name:[CUser DefaultUser].U_Name];
        }
        else 
        {
            UIAlertView *login = [[UIAlertView alloc] initWithTitle:@"提示" message:@"新浪微博分享功能未打开" delegate:nil
                                                  cancelButtonTitle:@"关闭" otherButtonTitles:nil];
            [login show];
            [login autorelease];
        }
    }
    //qq
    else if (1 == index)
    {
        if (1 == [[CUser DefaultUser].U_QqOn intValue])
        {
            [CQWeiBo DefaultQQwb].m_QWeiboDelegate = self;
            [[CQWeiBo DefaultQQwb] LoginQQWeibo:[CRootCtrlManager DefaultRootCtrl] Name:[CUser DefaultUser].U_Name];
        }
        else 
        {
            UIAlertView *login = [[UIAlertView alloc] initWithTitle:@"提示" message:@"腾讯微博分享功能未打开" delegate:nil
                                                  cancelButtonTitle:@"关闭" otherButtonTitles:nil];
            [login show];
            [login autorelease];
        }
    }
    //email
    else if (2 == index)
    {
        [self DidEmailShare];
    }
    else 
    {
        //
    }
    
    [[CRootCtrlManager DefaultRootCtrl] HiddenShareView];
}

-(void)DidLoginSinaWeibo:(CSinaWeibo *)sinaweibo State:(int)state
{
    if (0 == state)
    {
        CProduct *product = [m_Datas objectAtIndex:m_TabView.m_Gallery.m_FocusView.tag];
        NSData   *data    = [product GetProductImage];
        UIImage *image = [UIImage imageWithData:data];
        [[CSinaWeibo DefaultSinawb] ShareToSinaWeibo:product.P_Name ImageFile:image];
    }
}

-(void)DidLoginQQWeibo:(CQWeiBo *)qweibo State:(int)state
{
    if (0 == state)
    {
        CProduct *product = [m_Datas objectAtIndex:m_TabView.m_Gallery.m_FocusView.tag];
        NSString *path = [NSString stringWithFormat:@"%@/tmp/qwb.jpg", NSHomeDirectory()];
        NSData   *data = [product GetProductImage];
        [data writeToFile:path atomically:NO];
        [[CQWeiBo DefaultQQwb] ShareToQWeibo:product.P_Name ImageFile:path];
    }
}

//bottombar
-(void)OnBottomBarBtnDown:(int)index
{
    if ([m_Datas count] > 0)
    {
        CProduct *product    = [m_Datas objectAtIndex:m_TabView.m_Gallery.m_FocusView.tag];
        //CKey     *key        = nil;
        //NSMutableArray *keys = [NSMutableArray array];          
        //long            num  = 0;
        
        //eat
        /*if (0 == sender.tag)
        {
            product.P_Eat = [NSNumber numberWithLong:[product.P_Eat longValue]+1];
            num = [product.P_Eat longValue];
            m_Eatlb.text = [NSString stringWithFormat:@"%ld", num];
            
            //key = [[CKey alloc] initWithType:1 Value:product.P_Eat Name:@"P_Eat"];
        }
        //want
        else if (1 == sender.tag)
        {
            product.P_Want = [NSNumber numberWithLong:[product.P_Want longValue]+1];
            num = [product.P_Want longValue];
            m_Wantlb.text = [NSString stringWithFormat:@"%ld", num];
            
            //key = [[CKey alloc] initWithType:1 Value:product.P_Want Name:@"P_Want"];
        }
        //nice
        else if (2 == sender.tag)
        {
            product.P_Nice = [NSNumber numberWithLong:[product.P_Nice longValue]+1];
            num = [product.P_Nice longValue];
            m_Nicelb.text = [NSString stringWithFormat:@"%ld", num];
            
            //key = [[CKey alloc] initWithType:1 Value:product.P_Nice Name:@"P_Nice"];
        }*/
        
        if (Logined == [CUser DefaultUser].m_UType)
        {
            [product PublicationAppraisal:[CUser DefaultUser].U_Token SessionID:[CUser DefaultUser].U_Session Type:index];
        }
        else 
        {
            UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登陆..." delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
            [alter show];
            [alter autorelease];
        }
        
        /*[keys addObject:key];
        NSString *condition = [NSString stringWithFormat:@"P_AID==\"%ld\"", [product.P_AID longValue]];
        [CProduct UpdateProductInfo:@"Products" Where:condition Keys:keys];
        [key release];*/
    }
}

-(void)ShowBottomBar:(BOOL)isShow
{
    if (isShow)
    {
        m_BottomBar.hidden = NO;
    }
    else 
    {
        m_BottomBar.hidden = YES;
    }
}

//bigimageview
-(void)SetBigImageViewImage:(CProduct*)pdct
{
    if (m_bIsBigImageShow)
    {
        NSData *data = [pdct GetProductImage];
        if (data)
        {
            m_BigImage.image = [UIImage imageWithData:data];
        }
        else 
        {
            m_BigImage.image = [UIImage imageWithData:self.m_DfData];
        }
    }
}

-(void)ShowBigImageView:(UIImage*)image
{
    if (!m_bIsBigImageShow)
    {
        m_bIsBigImageShow = YES;
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDidStopSelector:@selector(DidBigImageViewShow)];
        m_BigImage.image = image;
        m_BigImage.alpha = 1.0;
        m_BigImageView.alpha = 1.0;
        [UIView commitAnimations];
    }
}

-(void)HiddenBigImageView
{
    if (1.0 == m_BigImage.layer.shadowOpacity)
    {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDidStopSelector:@selector(DidBigImageViewHidden)];
        m_BigImage.layer.shadowOpacity = 0.0;
        m_BigImage.transform = CGAffineTransformMakeScale(0.1, 0.1);
        [UIView commitAnimations];
    }
}

-(void)DidBigImageViewShow
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(DidBigImageShown)];
    m_BigImage.transform = CGAffineTransformMakeScale(1, 1);
    [UIView commitAnimations];
}

-(void)DidBigImageShown
{
   m_BigImage.layer.shadowOpacity = 1.0; 
}

-(void)DidBigImageViewHidden
{
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(DidBigImageHidden)];
    m_BigImage.alpha = 0.0;
    m_BigImageView.alpha = 0.0;
    [UIView commitAnimations];
}

-(void)DidBigImageHidden
{
    m_bIsBigImageShow = NO;
    m_BigImage.image = nil;
}

-(void)ItemPreViewDoubleTouch:(id)preview
{
    //UIImage *image = ((CItemPreView*)preview).m_CurrentImage.image;
    //[self ShowBigImageView:image];
}

//information
-(IBAction)OnResBtnDown:(UIButton*)sender
{
    CProduct *product = [m_Datas objectAtIndex:m_TabView.m_Gallery.m_FocusView.tag];
    
    UIAlertView *what = [[UIAlertView alloc] initWithTitle:@"界面是啥" message:product.P_ResName delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
    [what show];
    [what autorelease];
}

-(IBAction)OnPuberBtnDown:(UIButton*)sender
{    
    if (Logined == [CUser DefaultUser].m_UType)
    {
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDelegate:self];
        [UIView setAnimationDuration:0.4];
        [UIView setAnimationDidStopSelector:@selector(DidPuberInfoViewShow)];
        m_PubInfoView.center = CGPointMake(self.view.frame.size.width/2, m_PubInfoView.center.y);
        //[m_PubInfoView SetPuberInfoView:[m_Datas objectAtIndex:m_TabView.m_Gallery.m_FocusView.tag]];
        [UIView commitAnimations];
    }
    else 
    {
        UIAlertView *login = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请先登陆" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
        [login show];
        [login autorelease];
    }
}

-(void)DidPuberInfoViewShow
{
    [m_PubInfoView GetPubInfoFromSrv:[m_Datas objectAtIndex:m_TabView.m_Gallery.m_FocusView.tag]];
}

-(void)DidRetBtnDown
{
    [UIView beginAnimations:nil context:nil];
    m_PubInfoView.center = CGPointMake(m_PubInfoView.center.x+self.view.frame.size.width, m_PubInfoView.center.y);
    [UIView commitAnimations];
}

//地图
-(void)ShowMapView
{
    [m_Map.m_Pins removeAllObjects];
    m_MapAddr.text = [NSString stringWithFormat:@" 目前在:%@", [self GetUserPosition]];
    
    [UIView beginAnimations:nil context:nil];
    [UIView setAnimationDuration:0.5];
    [UIView setAnimationDelegate:self];
    [UIView setAnimationDidStopSelector:@selector(DidShowMapView)];
    m_MapPanel.center = CGPointMake(self.view.frame.size.width/2, m_MapPanel.center.y);
    [UIView commitAnimations];
}

-(void)DidShowMapView
{
    m_nModel = 1;
    
    NSArray *nodes = nil;
    
    //best 
    if (0 == m_TabView.m_Tab.m_nFocus)
    {
        nodes = [NSArray arrayWithArray:m_Datas];
    }
    //nearest
    else if (1 == m_TabView.m_Tab.m_nFocus)
    {
        nodes = [NSArray arrayWithArray:m_Datas];
    }
    //lastest
    else if (2 == m_TabView.m_Tab.m_nFocus)
    {
        nodes = [NSArray arrayWithArray:m_Datas];
    }
    //favorite
    else if (3 == m_TabView.m_Tab.m_nFocus)
    {
        nodes = [NSArray arrayWithArray:m_Datas];
    }
    //myupload
    else if (4 == m_TabView.m_Tab.m_nFocus)
    {
        nodes = [NSArray arrayWithArray:m_Datas];
    }
    //search
    else if (5 == m_TabView.m_Tab.m_nFocus)
    {
        nodes = [NSArray arrayWithArray:m_Datas];
    }
    else {;}
    
    m_Map.m_bIsShow = YES;
    
    [self SetLocations:nodes];
}

-(IBAction)OnMapViewBtnDown:(UIButton*)sender
{
    //return to mainpage
    if (4 == sender.tag)
    {
        [[NSNotificationCenter defaultCenter] removeObserver:self name:MSG_LOCATION_RET object:nil];
        
        [CLocator DefaultLocator].m_AddrInfo.m_strCity     = self.m_RqstAddr.m_strCity;
        [CLocator DefaultLocator].m_AddrInfo.m_strProvince = self.m_RqstAddr.m_strProvince;
        [CLocator DefaultLocator].m_AddrInfo.m_strCountry  = self.m_RqstAddr.m_strCountry;
        [CLocator DefaultLocator].m_AddrInfo.m_fX          = self.m_RqstAddr.m_fX;
        [CLocator DefaultLocator].m_AddrInfo.m_fY          = self.m_RqstAddr.m_fY;
        
        NSLog(@"\r\n\r\n地图切回到普通:%@\r\n\r\n", [CLocator DefaultLocator].m_AddrInfo.m_strCity);
        
        self.m_RqstAddr.m_strCity     = nil;
        self.m_RqstAddr.m_strProvince = nil;
        self.m_RqstAddr.m_strCountry  = nil;
        
        m_Map.m_bIsShow = NO;
        m_nModel = 0;
        m_Map.m_bTouchEnd = NO;
        [UIView beginAnimations:nil context:nil];
        [UIView setAnimationDuration:0.5];
        m_MapPanel.center = CGPointMake(m_MapPanel.center.x-m_MapPanel.frame.size.width, m_MapPanel.center.y);
        [UIView commitAnimations];
        
        [m_Map.m_Map removeAnnotations:m_Map.m_Pins];
        [m_Map.m_Pins removeAllObjects];
    }
}

-(void)SetLocations:(NSArray*)locations
{
    if ([locations count] > 0)
    {
        NSMutableArray *pins = [[NSMutableArray array] retain];
        CLLocationCoordinate2D location; 
        //CLLocationCoordinate2D center;
        MapAnnotation *pin = nil;
        int nCnt = [m_Map.m_Pins count];
        int nCount = 0;
        int nIndex = 0;
        double Radius   = 0.0;
        double distance = 0.0;
        BOOL bisnull = NO;
        
        //CProduct *pdct = [m_Datas objectAtIndex:self.m_TabView.m_Gallery.m_FocusView.tag];
        //center = CLLocationCoordinate2DMake([pdct.P_WDu doubleValue], [pdct.P_JDu doubleValue]);
        
        for (CProduct *product in locations)
        {
            if (nCount <= 50)
            {
                location.latitude  = [product.P_WDu floatValue];
                location.longitude = [product.P_JDu floatValue];
                
                //设置地图中心
                /*if ((center.latitude == 0.000000) && (center.longitude == 0.0000000))
                {
                    center = location;
                }
                */
                                
                //地图可视半径,是否零坐标
                if ((location.latitude == 0.000000) && (location.longitude == 0.0000000))
                {
                    bisnull = YES;
                }
                else 
                {
                    distance = [m_Map GetLocationDistance:m_Map.m_Map.centerCoordinate New:location];
                    bisnull = NO;
                    if (distance > Radius)
                    {
                        Radius = distance;
                    }
                }
                
                pin = [[MapAnnotation alloc] initWithCoordinate2D:location];
                pin.title = product.P_Name;
                pin.subtitle = product.P_ResName;
                if ((m_TabView.m_Gallery.m_FocusView.tag == nIndex) && (0 == [m_Map.m_Pins count]))
                {
                    pin.bIsSelected = YES;
                }
                pin.ntag = nCnt++;
                pin.nIndex = nIndex;
                pin.ncolor = 0;
                (bisnull) ? (pin.bIsNull = YES) : (pin.bIsNull = NO);
                [pins addObject:pin];
                [pin release];
          
                ++nCount;
            }
            else 
            {
                break;
            }
            
            ++nIndex;
        }
        
        //设置地图显示
        (Radius < 1000) ? (Radius = 1000) : (Radius);
        [m_Map.m_Map setRegion:MKCoordinateRegionMakeWithDistance(m_Map.m_Map.centerCoordinate, Radius, Radius) animated:YES];
        
        [m_Map.m_Pins addObjectsFromArray:pins];
        [m_Map.m_Map addAnnotations:pins];
        [pins release];
        
        [NSThread sleepForTimeInterval:1];
    }
}

-(void)InitMapData
{   
    if (1 == m_nModel)
    {
        [m_Map.m_Map removeAnnotations:m_Map.m_Pins];
        [m_Map.m_Pins removeAllObjects];
    }
    
    //[m_Map GetCurAddress:m_Map.m_Map.userLocation.coordinate];
}

-(void)LocationMsgListener:(NSNotification*)notification
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MSG_LOCATION_RET object:nil];
    [[NSNotificationCenter defaultCenter] removeObserver:self name:MSG_LOCATION_TIMEOUT object:nil];
    
    //suc
    if (notification.object)
    {
        m_bIsUpdate = YES;
        
        [[CRootCtrlManager DefaultRootCtrl] SetLoadViewTitle:@"数据获取中..."];
        //m_Address.text = [CLocator DefaultLocator].m_AddrInfo.m_strSum;
        
        //清空该用户缓存
        [[CRootCtrlManager DefaultRootCtrl] SetUserData:YES];
        
        //map
        if (1 == m_nModel)
        {
            m_Map.m_bTouchEnd = NO;
            m_Map.m_TimerID   = 0;
            
            if ((0.000000 != m_Map.m_Map.userLocation.location.coordinate.latitude) && (0.000000 != m_Map.m_Map.userLocation.location.coordinate.longitude))
            {
                [CUser DefaultUser].m_SelfPosition = m_Map.m_Map.userLocation.location.coordinate;
                [m_Map.m_Map setCenterCoordinate:m_Map.m_Map.userLocation.location.coordinate animated:YES];
            }
            else 
            {
                [CUser DefaultUser].m_SelfPosition = [CLocator DefaultLocator].m_Coordinate2D;
                [m_Map.m_Map setCenterCoordinate:[CUser DefaultUser].m_SelfPosition animated:YES];
            }
        }
        
        m_MapAddr.text = [NSString stringWithFormat:@" 目前在:%@", [CLocator DefaultLocator].m_AddrInfo.m_strCity];
        [self GetProductsFromServer:m_TabView.m_Tab.m_nFocus IsInit:YES Object:[NSNumber numberWithInt:0]];
    }
    else 
    {
        m_bIsUpdate = YES;
        
        [[CRootCtrlManager DefaultRootCtrl] SetLoadViewTitle:@"数据获取中..."];
        
        //map
        if (1 == m_nModel)
        {
            m_Map.m_bTouchEnd = NO;
            m_Map.m_TimerID   = 0;
            
            if ((0.000000 != m_Map.m_Map.userLocation.location.coordinate.latitude) && (0.000000 != m_Map.m_Map.userLocation.location.coordinate.longitude) && NormalSupport == [[CLocator DefaultLocator] CheckDevLocation])
            {
                [CUser DefaultUser].m_SelfPosition = m_Map.m_Map.userLocation.location.coordinate;
                [m_Map.m_Map setCenterCoordinate:m_Map.m_Map.userLocation.location.coordinate animated:YES];
            }
            else 
            {
                [m_Map.m_Map setCenterCoordinate:[CUser DefaultUser].m_SelfPosition animated:YES];
            }
        }
        
        [CLocator DefaultLocator].m_AddrInfo.m_strCity     = [NSString stringWithFormat:@"%@",[CUser DefaultUser].m_AddrInfo.m_strCity];
        [CLocator DefaultLocator].m_AddrInfo.m_strProvince = [NSString stringWithFormat:@"%@",[CUser DefaultUser].m_AddrInfo.m_strProvince];
        [CLocator DefaultLocator].m_AddrInfo.m_strCountry  = [NSString stringWithFormat:@"%@",[CUser DefaultUser].m_AddrInfo.m_strCountry];
        [CLocator DefaultLocator].m_AddrInfo.m_strSum      = [NSString stringWithFormat:@"%@",[CUser DefaultUser].m_AddrInfo.m_strSum];
        [CLocator DefaultLocator].m_AddrInfo.m_fX          = [CUser DefaultUser].m_AddrInfo.m_fX;
        [CLocator DefaultLocator].m_AddrInfo.m_fY          = [CUser DefaultUser].m_AddrInfo.m_fY;
        [CLocator DefaultLocator].m_Coordinate2D = CLLocationCoordinate2DMake([CUser DefaultUser].m_AddrInfo.m_fX, [CUser DefaultUser].m_AddrInfo.m_fY);
        
        NSLog(@"\r\n\r\n%@---%f---%f\r\n\r\n", [CLocator DefaultLocator].m_AddrInfo.m_strCity, [CLocator DefaultLocator].m_AddrInfo.m_fX, [CLocator DefaultLocator].m_AddrInfo.m_fY);
        
        m_MapAddr.text = [NSString stringWithFormat:@" 目前在:%@", [CLocator DefaultLocator].m_AddrInfo.m_strCity];
        [self GetProductsFromServer:m_TabView.m_Tab.m_nFocus IsInit:YES Object:[NSNumber numberWithInt:0]];
    }
    
    /*NSArray *rets = nil;
     int nIndex = m_NativeDBCnt.m_nOffset;
     m_NativeDBCnt.m_nLimit = 6;
     
     rets = [self GetProductsFromDB:nil OpIndex:m_TabView.m_Tab.m_nFocus];
     if (rets)
     {
     m_bIsUpdate = NO;
     [self InitMainPageView:NO];
     [self AddProductsToTabView:rets];
     m_NativeDBCnt.m_nOffset += 6;
     
     [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
     }
     else 
     {
     m_NativeDBCnt.m_nLimit = 0;
     m_NativeDBCnt.m_nOffset= nIndex;
     [self GetProductsFromServer:m_TabView.m_Tab.m_nFocus IsInit:YES];
     }*/
}

-(void)DidUpdateMapData:(CLLocationCoordinate2D)coordinate2D Radius:(float)radius State:(int)state Info:(long long)info
{
    if (m_TabView.m_Tab.m_nFocus < 4 && 1 == m_nModel)
    {
        //[[CRootCtrlManager DefaultRootCtrl] ShowLoadView:0.8 Title:@"正在获取数据..."];
        if (0 == state)
        {
            //
        }
        else if (1 == state)
        {
            m_bIsUpdate = YES;
            //cancel task
            if (m_Task)
            {
                [[CDownLoadManager DefaultDownLoadManager] CancelTask:m_Task];
            }
            
            NSLog(@"\r\n\r\nDidUpdateMapData-TimerID:%lld\r\n\r\n", info);
            if (!m_bIsLoading)
            {
                m_MapAddr.text = [NSString stringWithFormat:@" 目前在:%@", [CLocator DefaultLocator].m_AddrInfo.m_strCity];
                [self GetProductsFromServer:0/*m_nTabPosition*/ IsInit:YES Object:[NSNumber numberWithLongLong:info]];
            }
        }
        else if (2 == state)
        {
            //[[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
        }
        else {;}
    }
}

-(void)DidPinSelected:(int)index
{
    CGalleyItem *item = [[m_TabView.m_Gallery.m_RootPanel subviews] objectAtIndex:index];
    [item SetSelected];
    
    UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom];
    button.tag = 4;
    [self OnMapViewBtnDown:button];
}

//the data that get from server
-(void)CommitGetProducts:(NSString*)condition Action:(NSString*)action Code:(int)code Offset:(int)offset Limit:(int)limit Object:(id)object
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RequestError:) name:SRV_REQUEST_ERROR object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RequestTimeOut:) name:SRV_REQUEST_TIMEOUT object:nil];
    
    //best
    if (0 == code)
    {
        [self CommitBestRequest:offset Limit:limit Action:action Object:object];
    }
    //nearest
    else if (1 == code)
    {
        [self CommitNearestRequest:offset Limit:limit Action:action Object:object];
    }
    //newest
    else if (2 == code)
    {
        [self CommitNewestRequest:offset Limit:limit Action:action Object:object];
    }
    //search
    else if (3 == code)
    {
        [self CommitSearchRequest:offset Limit:limit Action:action Object:object];
    }
    else 
    {
        ;
    }
}

//best
-(void)CommitBestRequest:(int)offset Limit:(int)limit Action:(NSString*)action Object:(id)object
{
    NSLog(@"\n\r\n\r==========开始最好美食请求==========");
    NSMutableString *request = [NSMutableString string];
    NSString        *url     = nil;
    UCommand        com      = 0;
    NSString        *city    = nil;
    long            dis      = (long)m_Map.m_Radius;
    
    city = [NSString stringWithFormat:@"%@",[self GetUserPosition]];
    
    [request appendFormat:@"cursor=%d", offset];
    [request appendFormat:@"&offset=%d", limit];
    if (city)
    {
        [request appendFormat:@"&city=%@", city];
        [request appendFormat:@"&pic_distance=%ld", dis];
        [request appendFormat:@"&pic_x=%f", [CLocator DefaultLocator].m_Coordinate2D.latitude];
        [request appendFormat:@"&pic_y=%f", [CLocator DefaultLocator].m_Coordinate2D.longitude];
    }
    
    //普通模式
    if (0 == m_nModel)
    {
        [request appendFormat:@"&action=%@", action];
        
    }
    //地图模式
    else 
    {
        if (m_Map.m_Radius > 30000)
        {
            NSLog(@"进入地图模式，地图半径大于30000米");
            [request appendFormat:@"&action=%@", @"getMapArticle"];
            [request appendFormat:@"&appraise=%@", @"best"];
        }
        else 
        {
            [request appendFormat:@"&action=%@", action];
        }    
    }  
    
    url = URL_GETPRODUTS;
    com = GBestP;
    
    NSLog(@"<--------向服务器请求最好美食:%@___地图半径:%f", request, m_Map.m_Radius);
    
    [CUser DefaultUser].m_Target = self;
    [CUser DefaultUser].m_Action = @selector(DidReceiveProductsFromSvr:Info:);
    if (!(self.m_Task = [[CUser DefaultUser] GetProductsFromServer:request Url:url Command:com Object:object]))
    {
        m_bIsLoading = NO;
    }
    
    NSLog(@"==========结束最好美食请求==========\n\r\n\r");
}

//nearest
-(void)CommitNearestRequest:(int)offset Limit:(int)limit Action:(NSString*)action Object:(id)object
{
    NSLog(@"\n\r\n\r==========开始最近美食请求==========");
    NSMutableString *request = [NSMutableString string];
    NSString        *url     = nil;
    UCommand        com      = 0;
    long            dis      = (long)m_Map.m_Radius;
        
    [request appendFormat:@"cursor=%d", offset];
    [request appendFormat:@"&offset=%d", limit];
    [request appendFormat:@"&action=%@", action];
    
    //获取坐标
    //普通模式
    if (0 == m_nModel)
    {
        //[request appendFormat:@"&city=%@", city];
        [request appendFormat:@"&pic_x=%f", [CLocator DefaultLocator].m_Coordinate2D.latitude];
        [request appendFormat:@"&pic_y=%f", [CLocator DefaultLocator].m_Coordinate2D.longitude];
        [request appendFormat:@"&pic_distance=%ld", dis];
    }
    //地图模式
    else 
    {
        //[request appendFormat:@"&city=%@", [CLocator DefaultLocator].m_AddrInfo.m_strCity];
        [request appendFormat:@"&pic_x=%f", [CLocator DefaultLocator].m_Coordinate2D.latitude];
        [request appendFormat:@"&pic_y=%f", [CLocator DefaultLocator].m_Coordinate2D.longitude];
        [request appendFormat:@"&pic_distance=%ld", dis];
    }
    
    url = URL_GETNEAREST;
    com = GNearestP;
    
    //NSLog(@"<--------向服务器请求最近美食:%@___%f___没有地图模式地图半径大于30000米访问模式", request, m_Map.m_Radius);
    
    [CUser DefaultUser].m_Target = self;
    [CUser DefaultUser].m_Action = @selector(DidReceiveProductsFromSvr:Info:);
    if (!(self.m_Task = [[CUser DefaultUser] GetProductsFromServer:request Url:url Command:com Object:object]))
    {
        m_bIsLoading = NO;
    }
    
    NSLog(@"==========结束最近美食请求==========\n\r\n\r");
}

//newest
-(void)CommitNewestRequest:(int)offset Limit:(int)limit Action:(NSString*)action Object:(id)object
{
    NSLog(@"\n\r\n\r==========最新美食请求==========");
    NSMutableString *request = [NSMutableString string];
    NSString        *url     = nil;
    UCommand        com      = 0;
    NSString        *city    = nil;
    long            dis      = (long)m_Map.m_Radius;
    
    [request appendFormat:@"cursor=%d", offset];
    [request appendFormat:@"&offset=%d", limit];
    city = [NSString stringWithFormat:@"%@",[self GetUserPosition]];
    [request appendFormat:@"&city=%@", city];
        
    //地图模式
    if (1 == m_nModel)
    {
        [request appendFormat:@"&pic_distance=%ld", dis];
        [request appendFormat:@"&pic_x=%f", [CLocator DefaultLocator].m_Coordinate2D.latitude];
        [request appendFormat:@"&pic_y=%f", [CLocator DefaultLocator].m_Coordinate2D.longitude];
        
        if (m_Map.m_Radius > 30000)
        {
            NSLog(@"进入地图模式，地图半径大于30000米");
            [request appendFormat:@"&action=%@", @"getMapArticle"];
            [request appendFormat:@"&appraise=%@", @"newest"];
        }
        else 
        {
            [request appendFormat:@"&action=%@", action];
        }
    }
    //普通模式
    else 
    {
        [request appendFormat:@"&action=%@", action];
    }
    
    url = URL_GETPRODUTS;
    com = GLastestP;
    
    NSLog(@"<--------向服务器请求最新美食:%@___%f", request, m_Map.m_Radius);
    
    [CUser DefaultUser].m_Target = self;
    [CUser DefaultUser].m_Action = @selector(DidReceiveProductsFromSvr:Info:);
    if (!(self.m_Task = [[CUser DefaultUser] GetProductsFromServer:request Url:url Command:com Object:object]))
    {
        m_bIsLoading = NO;
    }
    
    NSLog(@"==========结束最新美食请求==========\r\n\n\r");
}

//search
-(void)CommitSearchRequest:(int)offset Limit:(int)limit Action:(NSString*)action Object:(id)object
{
    NSLog(@"\n\r\n\r==========开始搜索请求==========");
    NSMutableString *request = [NSMutableString string];
    NSString        *url     = nil;
    UCommand        com      = 0;
    
    //模糊搜索
    if ([action isEqualToString:OP_GETSEARCH_PRODUCT])
    {
        [request appendFormat:@"cursor=%d", offset];
        [request appendFormat:@"&offset=%d", limit];
        [request appendFormat:@"&action=%@", action];
        [request appendFormat:@"&value=%@", m_SearchView.m_SearchBar.text];
        [request appendFormat:@"&x=%f", [CUser DefaultUser].m_AddrInfo.m_fX];
        [request appendFormat:@"&y=%f", [CUser DefaultUser].m_AddrInfo.m_fY];

        url = URL_SEARCH;
        com = GSearchP;
    }
    //同名菜
    else 
    {
        [request appendFormat:@"cursor=%d", offset];
        [request appendFormat:@"&offset=%d", limit];
        [request appendFormat:@"&action=%@", action];
        [request appendFormat:@"&pic_name=%@", m_SearchView.m_SearchBar.text];
        
        url = URL_SEARCH_SAMENAME;
        com = GSearchP;
    }
    
    NSLog(@"<--------向服务器请求搜索美食:%@___%f", request, m_Map.m_Radius);
    
    [CUser DefaultUser].m_Target = self;
    [CUser DefaultUser].m_Action = @selector(DidReceiveProductsFromSvr:Info:);
    if (!(self.m_Task = [[CUser DefaultUser] GetProductsFromServer:request Url:url Command:com Object:object]))
    {
        m_bIsLoading = NO;
    }
    
    NSLog(@"==========结束搜索请求==========\r\n\n\r");
}

//add product
-(void)DidReceiveProductsFromSvr:(NSDictionary*)data Info:(id)info
{
    NSNumber *command = [info objectAtIndex:0];
    NSNumber *userinfo= [info objectAtIndex:1];
    NSString *message = nil;
    
    if (m_Command == [command shortValue])
    {
        int nErrorCode = [[data objectForKey:@"Msg_error"] intValue];
        
        if (0 == nErrorCode)
        {
            //map
            if (1 == m_nModel)
            {
                NSLog(@"%lld___%lld", m_Map.m_TimerID, [userinfo longLongValue]);
                if (m_Map.m_TimerID != [userinfo longLongValue])
                {
                    m_bIsLoading = NO;
                    [m_TabView HiddenIndicator];
                    return;
                }
            
                //记录地图当前位置
                self.m_RqstAddr.m_strCity     = [NSString stringWithFormat:@"%@",[CLocator DefaultLocator].m_AddrInfo.m_strCity];
                self.m_RqstAddr.m_strProvince = [NSString stringWithFormat:@"%@",[CLocator DefaultLocator].m_AddrInfo.m_strProvince];
                self.m_RqstAddr.m_strCountry  = [NSString stringWithFormat:@"%@",[CLocator DefaultLocator].m_AddrInfo.m_strCountry];
                self.m_RqstAddr.m_fX          = [CLocator DefaultLocator].m_AddrInfo.m_fX;
                self.m_RqstAddr.m_fY          = [CLocator DefaultLocator].m_AddrInfo.m_fY;
            }
            
            //NSLog(@"\n\r\n\r服务器返回的json数据内容:%@\n\r\n\r", data);
        
            //best
            if (GBestP == m_Command)
            {
                NSArray  *items   = [data objectForKey:@"Resource"];
                m_NetCnt.m_nTotal = [[data objectForKey:@"total"] intValue];
                
                NSLog(@"\n\r\n\r-------->收到服务器最好数据:%d(条)-共计:%d(条)-start\n\r", [items count], m_NetCnt.m_nTotal);
                [self DidReceiveBestDataFromSvr:items];
                NSLog(@"-------->收到服务器最好数据-end\r\n\n\r");
            }
            //nearest
            else if (GNearestP == m_Command)
            {
                NSArray  *items   = [data objectForKey:@"Resource"];
                m_NetCnt.m_nTotal = [[data objectForKey:@"total"] intValue];
                
                NSLog(@"\n\r\n\r-------->收到服务器最好数据:%d(条)-共计:%d(条)-start\n\r", [items count], m_NetCnt.m_nTotal);
                [self DidReceiveNearestDataFromSvr:items];
                NSLog(@"-------->收到服务器最好数据-end\r\n\n\r");
            }
            //lastest
            else if (GLastestP == m_Command)
            {
                NSArray  *items   = [data objectForKey:@"Resource"];
                m_NetCnt.m_nTotal = [[data objectForKey:@"total"] intValue];
                
                NSLog(@"\n\r\n\r-------->收到服务器最好数据:%d(条)-共计:%d(条)-start\n\r", [items count], m_NetCnt.m_nTotal);
                [self DidReceiveNewestDataFromSvr:items];
                NSLog(@"-------->收到服务器最好数据-end\r\n\n\r");
            }
            //search results
            else if (GSearchP == m_Command)
            {
                NSArray  *items   = [data objectForKey:@"Resource"];
                m_NetCnt.m_nTotal = [[data objectForKey:@"total"] intValue];
                
                NSLog(@"\n\r\n\r-------->收到服务器搜索结果数据:%d(条)-共计:%d(条)-start\n\r", [items count], m_NetCnt.m_nTotal);
                [self DidReceiveSearchDataFromSvr:items];
                NSLog(@"-------->收到服务器搜索结果数据-end\r\n\n\r");
            }
            else
            {
                return;
            }
        }
        //返回的条目数为0或者错误
        else 
        {
            //tab改变，没有美食
            if (m_bIsUpdate)
            {
                m_bIsUpdate = NO;
                
                if (GBestP == m_Command)
                {
                   if (18 == nErrorCode)
                   {
                       //定位，有网，该城市没有数据，未启动
                       if (![CRootCtrlManager DefaultRootCtrl].m_bIsActive)
                       {
                           //切换到无定位情况
                           m_bIsUpdate = NO;
                           [[CRootCtrlManager DefaultRootCtrl] ShowAlterView:@"你所在城市无数据,将为您提供其它数据." State:3];
                           message = nil;
                       }
                       else 
                       {
                           message = @"没啥好吃的";
                       }
                   }
                   else 
                   {
                      message = [data objectForKey:@"Msg"];
                   }
                    
                   [m_TabView.m_Tab SetFocus:m_nTabPosition];
                }
                //nearest
                else if (GNearestP == m_Command)
                {
                    if (18 == nErrorCode)
                    {
                        message = @"附近没啥好吃的";
                    }
                    else 
                    {
                        message = [data objectForKey:@"Msg"];
                    }
                    
                    [m_TabView.m_Tab SetFocus:m_nTabPosition];
                }
                //lastest
                else if (GLastestP == m_Command)
                {
                    if (18 == nErrorCode)
                    {
                        message = @"最近没啥好吃的";
                    }
                    else 
                    {
                        message = [data objectForKey:@"Msg"];
                    }
                    
                    [m_TabView.m_Tab SetFocus:m_nTabPosition];
                }
                //search
                else if (GSearchP == m_Command)
                {
                    //[self InitMainPageView:NO];
                    //显示搜索界面
                    [self performSelectorOnMainThread:@selector(SearchViewBecomeFirstResponse) withObject:nil waitUntilDone:YES];
                    message = @"没有找到美食.";
                }
                else{;}
                
                if (message) 
                {
                    UIAlertView *nodata = [[UIAlertView alloc] initWithTitle:@"提示" message:message delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
                    [nodata show];
                    [nodata autorelease];
                }
            }
            //更多数据
            else 
            {
                NSLog(@"\r\n\r\n没啥吃的\r\n\r\n");
            }
            
            m_bIsLoading = NO;
        }
        
        [m_TabView HiddenIndicator];
        [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
    }
    
    m_bIsFresh = NO;
    self.m_Task = nil;
}

//best
-(void)DidReceiveBestDataFromSvr:(NSArray*)products
{
    //判断数据是否有效
    if (!m_bIsUpdate)
    {
        //无效数据
        if (m_NetCnt.m_nOffset >= m_NetCnt.m_nTotal)
        {
            [m_TabView HiddenIndicator];
            [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
            
            return;
        }
    }
    else 
    {
        //clear buffer of best
        [[CDBManager ScheduledShareInstance] ClearTable:@"Best"];
    }
    
    //Clear best buffer
    if (m_bIsFresh)
    {
        [[CDBManager ScheduledShareInstance] ClearTable:@"Best"];
        [[CDBManager ScheduledShareInstance] ClearTable:@"Commentaries"];
        [[AppConfig DefaultAppConfig] RemovePathInApp:@"Documents" SubPath:@"DeliciousImages"];
        [[AppConfig DefaultAppConfig] CreatePathInApp:@"Documents" SubPath:@"DeliciousImages"];
        m_bIsFresh = NO;
    }
    
    //组装数据
    int nCnt = 0;
    CProduct *product = nil;
    NSMutableArray *res = [NSMutableArray array];
    for (NSDictionary *subdic in products) 
    {
        if (nCnt < 6)
        {
            product = [[CProduct alloc] init];
            [product SetProductWithDic:subdic Path:[AppConfig DefaultAppConfig].m_DelImagesPath];
            //NSLog(@"从服务器获得美食经信息__(latitude:%f, longtitude:%f),(名称:%@),(餐馆:%@),(地址:%@),(发布者:%@),(ID:%ld)\r\n\r\n", [product.P_WDu floatValue], [product.P_JDu floatValue], product.P_Name, product.P_ResName, product.P_Position, product.P_PubName, [product.P_AID longValue]);
            //NSLog(@"最好:%ld,好吃:%ld,好看:%ld", [product.P_Eat longValue], [product.P_Want longValue], [product.P_Nice longValue]);
            
            //save product to buffer(repeat data)
            if (0 == m_nModel/*[[CUser DefaultUser].m_AddrInfo.m_strCity isEqualToString:product.P_City]*/)
            {
                if (0 == [product SaveProduct:@"Best"])
                {
                    [res addObject:product];
                }
            }
            else 
            {
                [res addObject:product];
            }
            
            [product release];
        }
        else 
        {
            break;
        }
        
        ++nCnt;
    }
    
    [m_NetCnt GetAscNextLimit:m_NetCnt.m_nTotal Cnt:[products count]];
    
    //是否刷新mainpage
    if (m_bIsUpdate)
    {
        if ([res count] > 0)
        {
            [m_NetCnt InitAscWithCount:m_NetCnt.m_nTotal Limit:6];
            [m_NetCnt GetAscNextLimit:m_NetCnt.m_nTotal Cnt:[products count]];
            
            //m_Address.text = [CLocator DefaultLocator].m_AddrInfo.m_strSum;
            [self InitMainPageView:NO];
            [self AddProductsToTabView:res];
            self.m_FavoBtn.enabled = YES;
        }
        
        m_bIsUpdate = NO;
    }
    else
    {
        [self AddProductsToTabView:res];
    }
}

//nearest
-(void)DidReceiveNearestDataFromSvr:(NSArray*)products
{
    //判断数据是否有效
    if (!m_bIsUpdate)
    {
        //无效数据
        if (m_NetCnt.m_nOffset >= m_NetCnt.m_nTotal)
        {
            [m_TabView HiddenIndicator];
            [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
            
            return;
        }
    }
    else 
    {
        //clear buffer of near
        [[CDBManager ScheduledShareInstance] ClearTable:@"Nearest"];
    }
    
    //Clear nearest buffer
    if (m_bIsFresh)
    {
        [[CDBManager ScheduledShareInstance] ClearTable:@"Nearest"];
        [[CDBManager ScheduledShareInstance] ClearTable:@"Commentaries"];
        [[AppConfig DefaultAppConfig] RemovePathInApp:@"Documents" SubPath:@"DeliciousImages"];
        [[AppConfig DefaultAppConfig] CreatePathInApp:@"Documents" SubPath:@"DeliciousImages"];
        m_bIsFresh = NO;
    }
    
    //组装数据
    int nCnt = 0;
    CProduct *product = nil;
    NSMutableArray *res = [NSMutableArray array];
    for (NSDictionary *subdic in products) 
    {
        if (nCnt < 6)
        {
            product = [[CProduct alloc] init];
            [product SetProductWithDic:subdic Path:[AppConfig DefaultAppConfig].m_DelImagesPath];
            //NSLog(@"从服务器获得美食经信息__(latitude:%f, longtitude:%f),(名称:%@),(餐馆:%@),(地址:%@),(发布者:%@),(ID:%ld)\r\n\r\n", [product.P_WDu floatValue], [product.P_JDu floatValue], product.P_Name, product.P_ResName, product.P_Position, product.P_PubName, [product.P_AID longValue]);
            //NSLog(@"最好:%ld,好吃:%ld,好看:%ld", [product.P_Eat longValue], [product.P_Want longValue], [product.P_Nice longValue]);
            
            //save product to buffer(repeat data)
            if (0 == m_nModel/*[[CUser DefaultUser].m_AddrInfo.m_strCity isEqualToString:product.P_City]*/)
            {
                if (0 == [product SaveProduct:@"Nearest"])
                {
                    [res addObject:product];
                }
            }
            else 
            {
                [res addObject:product];
            }
            
            [product release];
        }
        else 
        {
            break;
        }
        
        ++nCnt;
    }
    
    [m_NetCnt GetAscNextLimit:m_NetCnt.m_nTotal Cnt:[products count]];
    
    //是否刷新mainpage
    if (m_bIsUpdate)
    {
        if ([res count] > 0)
        {
            [m_NetCnt InitAscWithCount:m_NetCnt.m_nTotal Limit:6];
            [m_NetCnt GetAscNextLimit:m_NetCnt.m_nTotal Cnt:[products count]];
            
            //m_Address.text = [CLocator DefaultLocator].m_AddrInfo.m_strSum;
            [self InitMainPageView:NO];
            [self AddProductsToTabView:res];
            self.m_FavoBtn.enabled = YES;
        }
        
        m_bIsUpdate = NO;
    }
    else
    {
        [self AddProductsToTabView:res];
    }
}

//newest
-(void)DidReceiveNewestDataFromSvr:(NSArray*)products
{
    //判断数据是否有效
    if (!m_bIsUpdate)
    {
        //无效数据
        if (m_NetCnt.m_nOffset >= m_NetCnt.m_nTotal)
        {
            [m_TabView HiddenIndicator];
            [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
            
            return;
        }
    }
    else 
    {
        //clear buffer of newest
        [[CDBManager ScheduledShareInstance] ClearTable:@"Newest"];
    }
    
    //Clear newest buffer
    if (m_bIsFresh)
    {
        [[CDBManager ScheduledShareInstance] ClearTable:@"Newest"];
        [[CDBManager ScheduledShareInstance] ClearTable:@"Commentaries"];
        [[AppConfig DefaultAppConfig] RemovePathInApp:@"Documents" SubPath:@"DeliciousImages"];
        [[AppConfig DefaultAppConfig] CreatePathInApp:@"Documents" SubPath:@"DeliciousImages"];
        m_bIsFresh = NO;
    }
    
    //组装数据
    int nCnt = 0;
    CProduct *product = nil;
    NSMutableArray *res = [NSMutableArray array];
    for (NSDictionary *subdic in products) 
    {
        if (nCnt < 6)
        {
            product = [[CProduct alloc] init];
            [product SetProductWithDic:subdic Path:[AppConfig DefaultAppConfig].m_DelImagesPath];
            //NSLog(@"从服务器获得美食经信息__(latitude:%f, longtitude:%f),(名称:%@),(餐馆:%@),(地址:%@),(发布者:%@),(ID:%ld)\r\n\r\n", [product.P_WDu floatValue], [product.P_JDu floatValue], product.P_Name, product.P_ResName, product.P_Position, product.P_PubName, [product.P_AID longValue]);
            //NSLog(@"最好:%ld,好吃:%ld,好看:%ld", [product.P_Eat longValue], [product.P_Want longValue], [product.P_Nice longValue]);
            
            //save product to buffer(repeat data)
            if (0 == m_nModel/*[[CUser DefaultUser].m_AddrInfo.m_strCity isEqualToString:product.P_City]*/)
            {
                if (0 == [product SaveProduct:@"Newest"])
                {
                    [res addObject:product];
                }
            }
            else 
            {
                [res addObject:product];
            }
            
            [product release];
        }
        else 
        {
            break;
        }
        
        ++nCnt;
    }
    
    [m_NetCnt GetAscNextLimit:m_NetCnt.m_nTotal Cnt:[products count]];
    
    //是否刷新mainpage
    if (m_bIsUpdate)
    {
        if ([res count] > 0)
        {
            [m_NetCnt InitAscWithCount:m_NetCnt.m_nTotal Limit:6];
            [m_NetCnt GetAscNextLimit:m_NetCnt.m_nTotal Cnt:[products count]];
            
            //m_Address.text = [CLocator DefaultLocator].m_AddrInfo.m_strSum;
            [self InitMainPageView:NO];
            [self AddProductsToTabView:res];
            self.m_FavoBtn.enabled = YES;
        }
        
        m_bIsUpdate = NO;
    }
    else
    {
        [self AddProductsToTabView:res];
    }
}

//search
-(void)DidReceiveSearchDataFromSvr:(NSArray*)products
{
    //判断数据是否有效
    if (!m_bIsUpdate)
    {
        //无效数据
        if (m_NetCnt.m_nOffset >= m_NetCnt.m_nTotal)
        {
            [m_TabView HiddenIndicator];
            [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
            
            return;
        }
    }
    
    //组装数据
    int nCnt = 0;
    CProduct *product = nil;
    NSMutableArray *res = [NSMutableArray array];
    for (NSDictionary *subdic in products) 
    {
        if (nCnt < 6)
        {
            product = [[CProduct alloc] init];
            [product SetProductWithDic:subdic Path:[AppConfig DefaultAppConfig].m_DelImagesPath];
            //NSLog(@"从服务器获得美食经信息__(latitude:%f, longtitude:%f),(名称:%@),(餐馆:%@),(地址:%@),(发布者:%@), (ID:%ld)\r\n\r\n", [product.P_WDu floatValue], [product.P_JDu floatValue], product.P_Name, product.P_ResName, product.P_Position, product.P_PubName, [product.P_AID longValue]);
            
            //save product to buffer(repeat data)
            /*if (0 == m_nModel *[[CUser DefaultUser].m_AddrInfo.m_strCity isEqualToString:product.P_City]*)
            {
                if (0 == [product SaveProduct:@"Search"])
                {
                    [res addObject:product];
                }
            }
            else 
            {
                [res addObject:product];
            }*/
            
            [res addObject:product];
            [product release];
        }
        else 
        {
            break;
        }
        
        ++nCnt;
    }
    
    [m_NetCnt GetAscNextLimit:m_NetCnt.m_nTotal Cnt:[products count]];
    
    //是否刷新mainpage
    if (m_bIsUpdate)
    {
        if ([res count] > 0)
        {
            [m_NetCnt InitAscWithCount:m_NetCnt.m_nTotal Limit:6];
            [m_NetCnt GetAscNextLimit:m_NetCnt.m_nTotal Cnt:[products count]];
            
            [self InitMainPageView:NO];
            [self AddProductsToTabView:res];
            
            [self performSelectorOnMainThread:@selector(HiddeSearchView) withObject:nil waitUntilDone:YES];
        }
        
        m_bIsUpdate = NO;
    }
    else
    {
        [self AddProductsToTabView:res];
    }
}

//upload
-(void)CommitMyUploadRequest:(int)offset Limit:(int)limit Action:(NSString*)action Object:(id)object
{
    NSLog(@"\n\r\n\r==========开始我的上传请求==========");
    NSString        *url     = nil;
    UCommand        com      = 0;
     NSMutableString *request = [NSMutableString string];
    
    [request appendFormat:@"cursor=%d", offset];
    [request appendFormat:@"&offset=%d", limit];
    [request appendFormat:@"&action=%@", action];
    [request appendFormat:@"&clientID=%@", [AppConfig DefaultAppConfig].m_strUDID];
    [request appendFormat:@"&mobikey=%@", [CUser DefaultUser].U_Token];
    [request appendFormat:@"&sessionid=%@", [CUser DefaultUser].U_Session];
    
    url = URL_GETMYUPLOAD;
    com = GUploadP;
    
    NSLog(@"<--------向服务器请求我的上传美食:%@", request);
    
    [CUser DefaultUser].m_Target = self;
    [CUser DefaultUser].m_Action = @selector(DidReceiveProductsFromSvr:Info:);
    if (!(self.m_Task = [[CUser DefaultUser] GetProductsFromServer:request Url:url Command:com Object:object]))
    {
        m_bIsLoading = NO;
    }
    
    NSLog(@"==========结束我的上传请求==========\r\n\r\n");
}

-(void)DidReceiveMyUploadDataFromSvr:(NSArray*)products
{
    //判断数据是否有效
    if (!m_bIsUpdate)
    {
        //无效数据
        if (m_NetCnt.m_nOffset >= m_NetCnt.m_nTotal)
        {
            [m_TabView HiddenIndicator];
            [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
            
            return;
        }
    }

    //组装数据
    int nCnt = 0;
    CProduct *product = nil;
    NSMutableArray *res = [NSMutableArray array];
    for (NSDictionary *subdic in products) 
    {
        if (nCnt < 6)
        {
            product = [[CProduct alloc] init];
            [product SetProductWithDic:subdic Path:[CUser DefaultUser].m_UploadPath];
            //NSLog(@"从服务器获得美食经信息__(latitude:%f, longtitude:%f),(名称:%@),(餐馆:%@),(地址:%@),(发布者:%@),(ID:%ld)\r\n\r\n", [product.P_WDu floatValue], [product.P_JDu floatValue], product.P_Name, product.P_ResName, product.P_Position, product.P_PubName, [product.P_AID longValue]);
            
            //save product to buffer(repeat data)
            if (0 == [product SaveProduct:[CUser DefaultUser].m_UploadTable])
            {
                [res addObject:product];
            }
            
            [product release];
        }
        else 
        {
            break;
        }
        
        ++nCnt;
    }
    
    [m_NetCnt GetAscNextLimit:m_NetCnt.m_nTotal Cnt:[products count]];
    
    //是否刷新mainpage
    if (m_bIsUpdate)
    {
        if ([res count] > 0)
        {
            [m_NetCnt InitAscWithCount:m_NetCnt.m_nTotal Limit:6];
            [m_NetCnt GetAscNextLimit:m_NetCnt.m_nTotal Cnt:[products count]];
            
            [self InitMainPageView:NO];
            [self AddProductsToTabView:res];
            self.m_FavoBtn.enabled = NO;
        }
        
        m_bIsUpdate = NO;
    }
    else
    {
        [self AddProductsToTabView:res];
    }
}
//favorite
-(void)CommitMyFavoriteRequest:(int)offset Limit:(int)limit Action:(NSString*)action Object:(id)object
{
    NSLog(@"\n\r\n\r==========开始我的收藏请求==========");
    NSString        *url     = nil;
    UCommand        com      = 0;
    NSMutableString *request = [NSMutableString string];
    
    [request appendFormat:@"cursor=%d", offset];
    [request appendFormat:@"&offset=%d", limit];
    [request appendFormat:@"&action=%@", action];
    [request appendFormat:@"&clientID=%@", [AppConfig DefaultAppConfig].m_strUDID];
    [request appendFormat:@"&mobikey=%@", [CUser DefaultUser].U_Token];
    [request appendFormat:@"&sessionid=%@", [CUser DefaultUser].U_Session];
    
    url = URL_GETPRODUTS;
    com = GFavoriteP;
    
    NSLog(@"<--------向服务器请求我的收藏美食:%@___%f", request, m_Map.m_Radius);
    
    [CUser DefaultUser].m_Target = self;
    [CUser DefaultUser].m_Action = @selector(DidReceiveProductsFromSvr:Info:);
    if (!(self.m_Task = [[CUser DefaultUser] GetProductsFromServer:request Url:url Command:com Object:object]))
    {
        m_bIsLoading = NO;
    }
    
    NSLog(@"==========结束我的收藏请求==========\r\n\n\r");
}

-(void)DidReceiveMyFavoriteDataFromSvr:(NSArray*)products
{
    //判断数据是否有效
    if (!m_bIsUpdate)
    {
        //无效数据
        if (m_NetCnt.m_nOffset >= m_NetCnt.m_nTotal)
        {
            [m_TabView HiddenIndicator];
            [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
            
            return;
        }
    }
    
    //组装数据
    int nCnt = 0;
    CProduct *product = nil;
    NSMutableArray *res = [NSMutableArray array];
    for (NSDictionary *subdic in products) 
    {
        if (nCnt < 6)
        {
            product = [[CProduct alloc] init];
            [product SetProductWithDic:subdic Path:[CUser DefaultUser].m_FavoritePath];
            //NSLog(@"从服务器获得美食经信息__(latitude:%f, longtitude:%f),(名称:%@),(餐馆:%@),(地址:%@),(发布者:%@),(ID:%ld)\r\n\r\n", [product.P_WDu floatValue], [product.P_JDu floatValue], product.P_Name, product.P_ResName, product.P_Position, product.P_PubName, [product.P_AID longValue]);
            
            //save product to buffer(repeat data)
            if (0 == [product SaveProduct:[CUser DefaultUser].m_FavoriteTable])
            {
                [res addObject:product];
            }
            
            [product release];
        }
        else 
        {
            break;
        }
        
        ++nCnt;
    }
    
    [m_NetCnt GetAscNextLimit:m_NetCnt.m_nTotal Cnt:[products count]];
    
    //是否刷新mainpage
    if (m_bIsUpdate)
    {
        if ([res count] > 0)
        {
            [m_NetCnt InitAscWithCount:m_NetCnt.m_nTotal Limit:6];
            [m_NetCnt GetAscNextLimit:m_NetCnt.m_nTotal Cnt:[products count]];
            
            [self InitMainPageView:NO];
            [self AddProductsToTabView:res];
            self.m_FavoBtn.enabled = NO;
        }
        
        m_bIsUpdate = NO;
    }
    else
    {
        [self AddProductsToTabView:res];
    }
}

-(void)CommitFavorite:(NSString*)paid
{
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RequestError:) name:SRV_REQUEST_ERROR object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(RequestTimeOut:) name:SRV_REQUEST_TIMEOUT object:nil];
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(DidReceiveFavorteNotification:) name:SRV_FAVORITE object:nil];
    
    NSMutableString *request = [NSMutableString stringWithCapacity:4];
    
    [request appendFormat:@"mobikey=%@", [CUser DefaultUser].U_Token];
    [request appendFormat:@"&sessionid=%@", [CUser DefaultUser].U_Session];
    [request appendFormat:@"&pic_id=%@", paid];
    [request appendFormat:@"&action=%@", @"setFavorites"];
    
    NSError *error = nil;
    if ((error = [[CUser DefaultUser] UserFavoriteProduct:request]))
    {
        NSLog(@"Error:%@(%d)", error.domain, error.code);
    }
}

-(void)DidReceiveFavorteNotification:(NSNotification*)notification
{
    NSDictionary *data = notification.object;
    int nCode = [[data objectForKey:@"Meg_error"] intValue];
    
    if (0 == nCode)
    {
        NSLog(@"\r\n\r\n收藏成功\r\n\r\n");
    }
    else 
    {
        NSLog(@"\r\n\r\n收藏失败\r\n\r\n");
    }
    
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SRV_FAVORITE object:nil];
}

//tabselected
-(void)GetProductsFromServer:(int)index IsInit:(BOOL)binit Object:(id)object
{
    NSString *action    = nil;
    
    //newest
    if (2 == index)
    {
        action = [[NSString alloc] initWithString:OP_GETNEWSET_PRODUCT];
        m_Command = GLastestP;
    }
    //nearest
    else if (1 == index)
    {
        action = [[NSString alloc] initWithString:OP_GETNEARSET_PRODUCT];
        m_Command = GNearestP;
    }
    //best
    else if (0 == index)
    {
        action = [[NSString alloc] initWithString:OP_GETBEST_PRODUCT];
        m_Command = GBestP;
    }
    //search
    else if (3 == index)
    {
        if (m_bIsVagueSearch)
        {
            action = [[NSString alloc] initWithString:OP_GETSEARCH_PRODUCT];
        }
        else 
        {
            action = [[NSString alloc] initWithString:OP_GETSAMENAME_PRODUCT];
        }
        m_Command = GSearchP;
    }
    //同名菜或者地方
    else if (4 == index)
    {
        //
    }
    else {;}
    
    if (binit)
    {
        [self CommitGetProducts:nil Action:action Code:index Offset:0 Limit:6 Object:object];
    }
    else 
    {
        [self CommitGetProducts:nil Action:action Code:index Offset:m_NetCnt.m_nOffset Limit:m_NetCnt.m_nLimit Object:object];
    }
    
    [action release];
}

-(NSArray*)GetProductsFromDB:(NSString*)condition OpIndex:(int)opindex
{
    NSArray *Results = nil;
    
    //newest
    if (2 == opindex)
    {
        m_Command = GLastestP;
        if (m_NativeDBCnt.m_nLimit > 0)
        {
            Results = [self GetNativeNewest:condition];
        }
    }
    //nearest
    else if (1 == opindex)
    {
        m_Command = GNearestP;
        if (m_NativeDBCnt.m_nLimit > 0)
        {
            Results = [self GetNativeNearest:condition];
        }
    }
    //best
    else if (0 == opindex)
    {
        m_Command = GBestP;
        if (m_NativeDBCnt.m_nLimit > 0)
        {
            Results = [self GetNativeBest:condition];
        }
    }
    //search
    else if (3 == opindex)
    {
        m_Command = GSearchP;
        if (m_NativeDBCnt.m_nLimit > 0)
        {
            Results = [self GetNativeSearch:condition];
        }
    }
    else {;}
    
    return Results;
}

//upload
-(void)TabUploadAction
{
    if (Logined == [CUser DefaultUser].m_UType)
    {
        NSArray *rets = nil;
        int nIndex = m_NativeDBCnt.m_nOffset;
        m_NativeDBCnt.m_nOffset = 0;
        m_NativeDBCnt.m_nLimit  = 6;
        
        rets = [self GetProductsFromDB:nil OpIndex:4];
        if (rets)
        {
            m_bIsUpdate = NO;
            [self InitMainPageView:NO];
            [self AddProductsToTabView:rets];
            m_NativeDBCnt.m_nOffset += [rets count];
            m_FavoBtn.enabled = NO;
            
            [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
        }
        else 
        {
            m_NativeDBCnt.m_nOffset = nIndex;
            m_NativeDBCnt.m_nLimit  = 0;
            [self GetProductsFromServer:4 IsInit:YES Object:[NSNumber numberWithInt:0]];
            //hchk-test-start
            //[m_TabView.m_Tab SetFocus:m_nTabPosition];
            //[[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
            //hchk-test-end
        }
    }
    else 
    {
        [m_TabView.m_Tab SetFocus:m_nTabPosition];
        [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
        
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"此功能只有登陆用户可用。" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
        [alter show];
        [alter autorelease];
    }
}

-(void)TabSearchAction:(int)value
{
    //继续搜索
    if (value > 0)
    {
        [[CRootCtrlManager DefaultRootCtrl] ShowLoadView:0.8 Title:@"结果搜索中..."];
        
        //m_TopLog.hidden = YES;
        
        if (m_TabView.m_Tab.m_nItemNum < 4)
            [m_TabView.m_Tab AddTabItem:@"搜索"];
        
        //self.m_nTabPosition = m_TabView.m_Tab.m_nFocus;
        [m_TabView.m_Tab SetFocus:3];
        m_bSearchSwitch = YES;
        self.m_bIsUpdate= YES;
        
        //重新搜索
        [self GetProductsFromServer:m_TabView.m_Tab.m_nFocus IsInit:YES Object:[NSNumber numberWithInt:0]];
        /*if (1 == value)
        {
            //clear buffer of searching
            [[CDBManager ScheduledShareInstance] ClearTable:@"Search"];
            [self GetProductsFromServer:m_TabView.m_Tab.m_nFocus IsInit:YES Object:[NSNumber numberWithInt:0]];
        }
        //获取本地历史记录
        else if (2 == value)
        {
            NSArray *rets = nil;
            m_NativeDBCnt.m_nOffset = 0;
            m_NativeDBCnt.m_nLimit  = 6;
            
            rets = [self GetProductsFromDB:nil OpIndex:5];
            if (rets)
            {
                [self InitMainPageView:NO];
                [self AddProductsToTabView:rets];
                m_NativeDBCnt.m_nOffset += 6;
            }
            [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
        }
        else {;}*/
    }
    //取消搜索
    else 
    {
        //m_TopLog.hidden = NO;
        
        self.m_nTabPosition = 1;
        [m_TabView.m_Tab SetFocus:0];
        m_bSearchSwitch = NO;
        self.m_bIsUpdate= YES;
        
        if (m_TabView.m_Tab.m_nItemNum > 3)
            [m_TabView.m_Tab DelTabItem:3];
        
        //clear buffer of searching
        //[[CDBManager ScheduledShareInstance] ClearTable:@"Search"];
        self.m_SearchValue = nil;
        m_SearchView.m_SearchBar.text = nil;
        m_SearchCover.alpha = 0.0;
        
        [[CRootCtrlManager DefaultRootCtrl] ShowLoadView:0.8 Title:@"数据加载中..."];
        [self TabBestAction];
    }
}

-(NSArray*)GetNativeSearch:(NSString*)condition
{
    NSArray *rets = nil;
    
    rets = [CProduct GetLimitProducts:@"Search" Where:condition Offset:m_NativeDBCnt.m_nOffset Limit:m_NativeDBCnt.m_nLimit];
    
    return rets;
}

-(NSArray*)GetNativeUpload:(NSString*)condition
{
    NSArray *rets = nil;
    
    NSString *tablename = [NSString stringWithFormat:@"%@_upload", [CUser DefaultUser].U_Name];
    rets = [CProduct GetLimitProducts:tablename Where:condition Offset:m_NativeDBCnt.m_nOffset Limit:m_NativeDBCnt.m_nLimit];
    
    return rets;
}

//favorite
-(void)TabFavoriteAction
{
    if (Logined == [CUser DefaultUser].m_UType)
    {
        NSArray *rets = nil;
        int nIndex = m_NativeDBCnt.m_nOffset;
        m_NativeDBCnt.m_nOffset = 0;
        m_NativeDBCnt.m_nLimit  = 6;
        
        rets = [self GetProductsFromDB:nil OpIndex:3];
        if (rets)
        {
            m_bIsUpdate = NO;
            [self InitMainPageView:NO];
            [self AddProductsToTabView:rets];
            m_NativeDBCnt.m_nOffset += [rets count];
            m_FavoBtn.enabled = NO;
            
            [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
        }
        else 
        {
            m_NativeDBCnt.m_nOffset = nIndex;
            m_NativeDBCnt.m_nLimit  = 0;
            [self GetProductsFromServer:3 IsInit:YES Object:[NSNumber numberWithInt:0]];
            //hchk-test-start
            //[m_TabView.m_Tab SetFocus:m_nTabPosition];
            //[[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
            //hchk-test-end
        }
    }
    else 
    {
        [m_TabView.m_Tab SetFocus:m_nTabPosition];
        [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
        
        UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"此功能只有登陆用户可用。" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
        [alter show];
        [alter autorelease];
    }
}

-(NSArray*)GetNativeFavorite:(NSString*)condition
{
    NSArray *rets = nil;
    
    NSString *tablename = [NSString stringWithFormat:@"%@_favorite", [CUser DefaultUser].U_Name];
    rets = [CProduct GetLimitProducts:tablename Where:condition Offset:m_NativeDBCnt.m_nOffset Limit:m_NativeDBCnt.m_nLimit];
    
    return rets;
}

//lastest
-(void)TabNewestAction
{
    NSArray *rets = nil;
    int nIndex = m_NativeDBCnt.m_nOffset;
    m_NativeDBCnt.m_nOffset = 0;
    m_NativeDBCnt.m_nLimit  = 6;
    
    //普通模式首先从本地提取数据
    if (0 == m_nModel && ![AppConfig DefaultAppConfig].m_bIsNetWork)
    {
        rets = [self GetProductsFromDB:nil OpIndex:2];
        //本地无数据则向服务器请求
        if (rets)
        {
            m_bIsUpdate = NO;
            [self InitMainPageView:NO];
            [self AddProductsToTabView:rets];
            m_NativeDBCnt.m_nOffset += [rets count];
            m_FavoBtn.enabled = YES;
            
            [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
        }
        else 
        {
            m_bIsUpdate = NO;
            m_NativeDBCnt.m_nOffset = nIndex;
            [m_TabView.m_Tab SetFocus:m_nTabPosition];
            [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
        }
    }
    //地图模式
    else 
    {
        [[CDownLoadManager DefaultDownLoadManager] CancelTask:m_Task];
        m_Map.m_TimerID = 0;
        self.m_Task = nil;
        [m_TabView HiddenIndicator];
    }
    
    [self GetProductsFromServer:2 IsInit:YES Object:[NSNumber numberWithInt:0]];
}

-(NSArray*)GetNativeNewest:(NSString*)condition
{
    NSArray *rets = nil;
    
    rets = [CProduct GetLimitProducts:@"Newest" Where:condition Offset:m_NativeDBCnt.m_nOffset Limit:m_NativeDBCnt.m_nLimit];

    return rets;
}

//best
-(void)TabBestAction
{
    NSArray *rets = nil;
    int nIndex = m_NativeDBCnt.m_nOffset;
    m_NativeDBCnt.m_nOffset = 0;
    m_NativeDBCnt.m_nLimit  = 6;
    
    //普通模式首先从本地提取数据，无网络
    if (0 == m_nModel && ![AppConfig DefaultAppConfig].m_bIsNetWork)
    {
        rets = [self GetProductsFromDB:nil OpIndex:0];
        if (rets)
        {
            //本地无数据则向服务器请求
            if (rets)
            {
                m_bIsUpdate = NO;
                [self InitMainPageView:NO];
                [self AddProductsToTabView:rets];
                m_NativeDBCnt.m_nOffset += [rets count];
                m_FavoBtn.enabled = YES;
                
                [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
            }
        }
        //本地无数据，返回上一tab
        else 
        {
            m_NativeDBCnt.m_nOffset = nIndex;
            m_bIsUpdate = NO;
            [m_TabView.m_Tab SetFocus:m_nTabPosition];
            [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
        }
        
        return;
    }
    //地图模式
    else 
    {
        [[CDownLoadManager DefaultDownLoadManager] CancelTask:m_Task];
        m_Map.m_TimerID = 0;
        self.m_Task = nil;
        [m_TabView HiddenIndicator];
    }
    
    [self GetProductsFromServer:0 IsInit:YES Object:[NSNumber numberWithInt:0]];
}

-(NSArray*)GetNativeBest:(NSString*)condition
{
    NSArray *rets = nil;

    rets = [CProduct GetLimitProducts:@"Best" Where:condition Offset:m_NativeDBCnt.m_nOffset Limit:m_NativeDBCnt.m_nLimit];

    return rets;
}

//nearest
-(void)TabNearestAction
{    
    NSArray *rets = nil;
    int nIndex = m_NativeDBCnt.m_nOffset;
    m_NativeDBCnt.m_nOffset = 0;
    m_NativeDBCnt.m_nLimit  = 6;
    
    //普通模式首先从本地提取数据
    if (0 == m_nModel && ![AppConfig DefaultAppConfig].m_bIsNetWork)
    {
        rets = [self GetProductsFromDB:nil OpIndex:1];
        //本地无数据则向服务器请求数据
        if (rets)
        {
            m_bIsUpdate = NO;
            [self InitMainPageView:NO];
            [self AddProductsToTabView:rets];
            m_NativeDBCnt.m_nOffset += [rets count];
            m_FavoBtn.enabled = YES;
            
            [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
        }
        else
        {
            m_bIsUpdate = NO;
            m_NativeDBCnt.m_nOffset = nIndex;
            [m_TabView.m_Tab SetFocus:m_nTabPosition];
            [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
        }
        
        return;
    }
    //地图模式
    else 
    {
        [[CDownLoadManager DefaultDownLoadManager] CancelTask:m_Task];
        m_Map.m_TimerID = 0;
        self.m_Task = nil;
        [m_TabView HiddenIndicator];
    }
    
    [self GetProductsFromServer:1 IsInit:YES Object:[NSNumber numberWithInt:0]];
}

-(NSArray*)GetNativeNearest:(NSString*)condition
{
    NSArray *rets = nil;
    
    rets = [CProduct GetLimitProducts:@"Nearest" Where:condition Offset:m_NativeDBCnt.m_nOffset Limit:m_NativeDBCnt.m_nLimit];
    
    return rets;
}

//network glob
-(void)RequestError:(NSNotification*)mes
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SRV_REQUEST_ERROR object:nil];
    
    [self performSelectorOnMainThread:@selector(UpDateUIWhenRequestError:) withObject:mes waitUntilDone:YES];
}

-(void)UpDateUIWhenRequestError:(id)object
{
    NSNotification *mes = object;
    NSArray *rets = mes.object;
    NSNumber*other= [rets objectAtIndex:0];
    NSNumber*info = [rets objectAtIndex:1];
    
    //tab
    if (GLastestP == [other shortValue] || GNearestP == [other shortValue] || GBestP == [other shortValue] || GSearchP == [other shortValue])
    {
        m_bIsLoading = NO;
        
        if (1 == m_nModel)
        {
            NSLog(@"\r\n\r\nError:%lld___%lld\r\n\r\n", m_Map.m_TimerID, [info longLongValue]);
            if (m_Map.m_TimerID != [info longLongValue]  && 0 != m_Map.m_TimerID)
            {
                NSLog(@"\r\n\r\n地图超时\r\n\r\n");
            }
            else 
            {
                if (self.m_RqstAddr.m_strCity)
                {
                    NSLog(@"\r\n\r\nOnMapViewBtnDown:%@__%@\r\n\r\n", [CLocator DefaultLocator].m_AddrInfo.m_strCity, self.m_RqstAddr.m_strCity);
                    
                    [CLocator DefaultLocator].m_AddrInfo.m_strCity     = self.m_RqstAddr.m_strCity;
                    [CLocator DefaultLocator].m_AddrInfo.m_strProvince = self.m_RqstAddr.m_strProvince;
                    [CLocator DefaultLocator].m_AddrInfo.m_strCountry  = self.m_RqstAddr.m_strCountry;
                    [CLocator DefaultLocator].m_AddrInfo.m_fX          = self.m_RqstAddr.m_fX;
                    [CLocator DefaultLocator].m_AddrInfo.m_fY          = self.m_RqstAddr.m_fY;
                    
                    NSLog(@"\r\n\r\nOnMapViewBtnDown:%@__%@\r\n\r\n", [CLocator DefaultLocator].m_AddrInfo.m_strCity, self.m_RqstAddr.m_strCity);
                    
                    self.m_RqstAddr.m_strCity     = nil;
                    self.m_RqstAddr.m_strProvince = nil;
                    self.m_RqstAddr.m_strCountry  = nil;
                }
            }
        }
        
        [m_TabView HiddenIndicator];
        [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
    }
    
    if (m_bIsUpdate)
    {
        [m_TabView.m_Tab SetFocus:m_nTabPosition];
        
        if ([CRootCtrlManager DefaultRootCtrl].m_bIsActive)
        {
            UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请求远程服务器错误，稍后再试（CMainPageCtrl-Error）。" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
            //[alter show];
            [alter autorelease];
        }
        else 
        {
            [[CRootCtrlManager DefaultRootCtrl] ShowAlterView:@"请求远程服务器超时，稍后再试。(CRootManagerCtrl-Error)" State:2];
        }
        
        m_bIsFresh = NO;
        m_bIsUpdate = NO;
    }
    
    self.m_Task = nil;
}

-(void)RequestTimeOut:(NSNotification*)mes
{
    [[NSNotificationCenter defaultCenter] removeObserver:self name:SRV_REQUEST_TIMEOUT object:nil];
    
    [self performSelectorOnMainThread:@selector(UpdateUIWhenRequestTimeout:) withObject:mes waitUntilDone:YES];
}

-(void)UpdateUIWhenRequestTimeout:(id)object
{
    NSNotification *mes = object;
    NSArray *rets = mes.object;
    NSNumber*other= [rets objectAtIndex:0];
    NSNumber*info = [rets objectAtIndex:1];
    
    //tab
    if (GLastestP == [other shortValue] || GNearestP == [other shortValue] || GBestP == [other shortValue] || GSearchP == [other shortValue])
    {
        m_bIsLoading = NO;
        
        NSLog(@"\r\n\r\nTimeOut:%lld___%lld\r\n\r\n", m_Map.m_TimerID, [info longLongValue]);
        if (1 == m_nModel)
        {
            if (!info)
            {
                NSLog(@"\r\n\r\nTimerID is null");
            }
            
            if (m_Map.m_TimerID != [info longLongValue] && 0 != m_Map.m_TimerID)
            {
                NSLog(@"\r\n\r\nTimerID is bad");
            }
            else 
            {
                if (self.m_RqstAddr.m_strCity)
                {
                    NSLog(@"\r\n\r\nOnMapViewBtnDown:%@__%@\r\n\r\n", [CLocator DefaultLocator].m_AddrInfo.m_strCity, self.m_RqstAddr.m_strCity);
                    
                    [CLocator DefaultLocator].m_AddrInfo.m_strCity     = self.m_RqstAddr.m_strCity;
                    [CLocator DefaultLocator].m_AddrInfo.m_strProvince = self.m_RqstAddr.m_strProvince;
                    [CLocator DefaultLocator].m_AddrInfo.m_strCountry  = self.m_RqstAddr.m_strCountry;
                    [CLocator DefaultLocator].m_AddrInfo.m_fX          = self.m_RqstAddr.m_fX;
                    [CLocator DefaultLocator].m_AddrInfo.m_fY          = self.m_RqstAddr.m_fY;
                    
                    NSLog(@"\r\n\r\nOnMapViewBtnDown:%@__%@\r\n\r\n", [CLocator DefaultLocator].m_AddrInfo.m_strCity, self.m_RqstAddr.m_strCity);
                    
                    self.m_RqstAddr.m_strCity     = nil;
                    self.m_RqstAddr.m_strProvince = nil;
                    self.m_RqstAddr.m_strCountry  = nil;
                }
            }
        }
        
        [m_TabView HiddenIndicator];
        [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
    }
    
    if (m_bIsUpdate)
    {
        [m_TabView.m_Tab SetFocus:m_nTabPosition];
        
        if ([CRootCtrlManager DefaultRootCtrl].m_bIsActive)
        {
            UIAlertView *alter = [[UIAlertView alloc] initWithTitle:@"提示" message:@"请求远程服务器超时，稍后再试。(CMainPageCtrl-TimeOut)" delegate:nil cancelButtonTitle:@"关闭" otherButtonTitles:nil];
            [alter show];
            [alter autorelease];
        }
        else 
        {
            [[CRootCtrlManager DefaultRootCtrl] ShowAlterView:@"请求远程服务器超时，稍后再试。(CRootManagerCtrl-Timeout)" State:1];
        }
        
        m_bIsFresh = NO;
        m_bIsUpdate = NO;
    }
    
    self.m_Task = nil;
}

//shake
-(void)FreshMianPage:(BOOL)isshowindicator
{
    m_bIsShake = NO;
    
    if (isshowindicator)
        [[CRootCtrlManager DefaultRootCtrl] ShowLoadView:0.8 Title:@"数据刷新中..."];
    
    m_bIsUpdate = YES;
    m_bIsFresh  = YES;
    
    //best
    if (0 == m_TabView.m_Tab.m_nFocus)
    {
        [self FreshBestAction];
    }
    //nearest
    else if (1 == m_TabView.m_Tab.m_nFocus)
    {
        [self FreshNearestAction];
    }
    //newest
    else if (2 == m_TabView.m_Tab.m_nFocus)
    {
        [self FreshNewestAction];
    }
    else
    {
        m_bIsUpdate = NO;
        m_bIsFresh  = NO;
        [[CRootCtrlManager DefaultRootCtrl] HiddenLoadView];
    }
    
    m_bIsShake = YES;
}

//best
-(void)FreshBestAction
{
    [self GetProductsFromServer:0 IsInit:YES Object:[NSNumber numberWithInt:0]];
}

//nearest
-(void)FreshNearestAction
{
    [self GetProductsFromServer:1 IsInit:YES Object:[NSNumber numberWithInt:0]];
}

//newest
-(void)FreshNewestAction
{
    [self GetProductsFromServer:2 IsInit:YES Object:[NSNumber numberWithInt:0]];
}

//touches
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{
    //
}

-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
}

- (void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration 
{
    //NSLog(@"shake:%@", (m_bIsShake) ? (@"YES") : (@"NO"));
    //NSLog(@"fresh:%@", (m_bIsFresh) ? (@"YES") : (@"NO"));
    if (m_bIsShake && !m_bIsFresh && (0 == m_nModel))
    {
        NSDate *now = [[NSDate alloc] init];
        
        //摇晃 １.５秒内
        NSDate *checkDate = [[NSDate alloc] initWithTimeInterval:1.0f sinceDate:m_ShakeStart];
        //超过１.５秒  重计算晃动次数
        if ([now compare:checkDate] == NSOrderedDescending || m_ShakeStart == nil)
        {
            m_nShakeCnt = 0;
            [m_ShakeStart release];
            m_ShakeStart = [[NSDate alloc] init];
        }
        [now release];
        [checkDate release];
 
        // 三轴摇晃的G力超过２则 列入计次
        if (fabsf(acceleration.x) > 1.0)
        {
            m_nShakeCnt++;
            if (m_nShakeCnt > 20)
            {
                m_nShakeCnt = 0;
                [m_ShakeStart release];
                m_ShakeStart = [[NSDate alloc] init];
                
                //mainpage显示下刷新
                if (![CMainPageCtrl DefaultMainPageCtrl].m_bIsHidden)
                {
                    [self FreshMianPage:YES];
                }
            }
        }
    }
}

@end
